简体   繁体   English

结构的重新分配使程序崩溃

[英]Deallocation of a structure keeps crashing program

So I'm trying to deallocate memory from a vector structure. 所以我试图从向量结构中释放内存。 It works fine when there's is a vector of 3 or less. 当向量为3或更小时,它可以正常工作。 However, when it is brought up to 4 or higher, and I try calling the deallocate function, it crashes. 但是,当它达到4或更高时,我尝试调用deallocate函数,它将崩溃。 I'm not entirely sure if I'm doing the deconstruction right and I need a hint as to where it is gone wrong here... 我不确定我是否正确地执行了解构操作,我需要提示一下这里哪里出错了...

void dealloc_vec(Vector * myVector)
{


myVector->size = 0;
//Delete the array of Vectors.
delete(myVector->vectorArray);
//Finally delete the entire vector.
delete(myVector);
}

And my structure is this 我的结构是这样

struct Vector
{
unsigned int size;
Elem *vectorArray;
};

Elem is a float. 元素是浮游生物。 Whenever a greater size than 3 is created it crashes the program before exiting. 只要创建的大小大于3,它就会在退出之前使程序崩溃。 We're using procedural c++ right. 我们正在使用过程性的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 and getInt 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;
}

If you allocated it by [] such as new Elem [x] then you should de-allocated it by 如果您是通过[]例如new Elem [x]分配的,则应该通过

delete [] myVector->vectorArray;

You can use std::vector to make your coding easier. 您可以使用std::vector编码。 Or even std::unique_ptr 甚至std::unique_ptr

std::unique_ptr<Elem[]> vectorArray(new Elem[x]);

Add a constructor to your struct that initialises the members. 在您的struct中添加一个初始化成员的构造struct vectorArray initially points to random memory locations and deleting those will cause undefined behaviour. vectorArray最初指向随机内存位置,删除这些位置将导致未定义的行为。

struct Vector
{
  Vector() : size(0), vectorArray(NULL) {}

  unsigned int size;
  Elem *vectorArray;
};

try this instead 试试这个代替

Vector *alloc_vec(void)
{
  //create a vector
  Vector *temp_Vector = new Vector;  // don't use ()

  temp_Vector->size = getInt((char*)"Please enter a value: ");
  temp_Vector->vectorArray =  new float[temp_Vector->size];

  for(unsigned int i = 0; i < temp_Vector->size; i++)
  {
    printf("Vector Element %d: ",i);
    temp_Vector->vectorArray[i] = getFloat((char*)"");
  }
  return temp_Vector;
}

then in dealloc 然后在dealloc

void dealloc_vec(Vector * myVector)
{
  myVector->size = 0; // there is no need for this
  //Delete the array of Vectors.
  delete [] myVector->vectorArray;  // no need for the ()
  //Finally delete the entire vector.
  delete myVector;
}

EDIT: 编辑:

your getInt/getFloat look a bit wrong 您的getInt / getFloat看起来有点错误

sscanf(size, "%i", &myInput);
//Size cannot be greater than 65535 or less than 0.
if(atoi(size) > 65535)

instead simply do something like this 而是简单地做这样的事情

int getInt(const char* prompt) 
{ 
  int n = 0;
  char buf[32]; 
  do
  {
    printf( "%s", prompt ); 
    fgets( buf, sizeof(buf), stdin ); 
    n = atoi(buf); // will ignore the \n
  }
  while ( n > 65535 );
  return n; 
}

for float just replace atoi with atof (and the limit if appropriate). 对于浮点数,只需将atoi替换为atof(以及相应的限制)。 note that atoi and atof return 0 if text is entered so you may want to check if >0 请注意,如果输入了文本,则atoi和atof返回0,因此您可能要检查> 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM