所以我试图从向量结构中释放内存。当向量为 3 或更少时,它工作正常。但是,当它达到 4 或更高时,我尝试调用 deallocate 函数,它崩溃了。我不完全确定我是否正确地进行解构,我需要提示这里哪里出了问题......
void dealloc_vec(Vector * myVector)
{
myVector->size = 0;
//Delete the array of Vectors.
delete(myVector->vectorArray);
//Finally delete the entire vector.
delete(myVector);
}
我的结构是这样的
struct Vector
{
unsigned int size;
Elem *vectorArray;
};
Elem 是一个浮点数。每当创建大于 3 的大小时,它都会在退出之前使程序崩溃。我们正在使用程序 c++ 对。
Vector *alloc_vec(void)
{
//create a vector
Vector *temp_Vector = new Vector();
//Using getInt from above to grab values for the size of vector, if given 0 it will just be a 0 vector.
temp_Vector->size = getInt((char*)"Please enter a value: ");
/*Test to see if it is less than zero, if it is program will halt.
assert(temp_Vector->size >= 0);
No need to check as unsigned int cannot be negative according to Wtype-limits
The size of vectorArray is now initialized from the size parameter of the structure.*/
temp_Vector->vectorArray = new float(temp_Vector->size);
//Loop through each element and assign a value from the user using getFloat (It looks cleaner with having separate functions).
for(unsigned int i = 0; i < temp_Vector->size; i++)
{
printf("Vector Element %d: ",i);
temp_Vector->vectorArray[i] = getFloat((char*)"");
}
//return the new vector.
return temp_Vector;
}
getFloat 和 getInt
float getFloat(char* promptMessage)
{
assert(promptMessage != NULL);
float myInput;
char size[100];
bool sucessful = false;
do
{
printf("%s", promptMessage);
//Use fgets to get the input from stdin.
fgets(size, 100, stdin);
//Check if value is anything but zero, if it isn't use this.
if(sscanf(size, "%f", &myInput) == 1)
{
myInput = atof(size);
sucessful = true;
}
else
{
printf("\nPlease enter a correct number: ");
}
}while(!sucessful);
return myInput;
}
int getInt(char* promptMessage)
{
assert(promptMessage != NULL);
int myInput;
char size[100];
bool sucessful = false;
do
{
printf("%s", promptMessage);
fgets(size, 100, stdin);
//Get the size using fgets and sscanf
sscanf(size, "%i", &myInput);
//Size cannot be greater than 65535 or less than 0.
if(atoi(size) > 65535)
{
printf("The chosen value is too large!\n");
}
else if(atoi(size) < 0)
{
printf("Error! Value is too small!\n");
}
//If sscanf is anything but a number, don't do this.
else if(sscanf(size, "%i", &myInput) == 1)
{
myInput = atoi(size);
sucessful = true;
}
else
{
printf("\nPlease enter a correct number: ");
}
}while(!sucessful);
return myInput;
}