简体   繁体   English

如何将动态分配的内存释放到struct中的数组?

[英]How to free a dynamically allocated memory to an array inside a struct?

I'm trying to free the memory of the allocated array inside struct _Stack , but the program keeps crashing 我正在尝试释放struct _Stack中已分配数组的内存,但程序不断崩溃

typedef struct _Stack
{
    int top;
    unsigned int capacity;
    int* arr;
}_Stack;

_Stack* createStack(int capacity)
{
    _Stack* stack = (_Stack*) malloc(sizeof(_Stack));
    stack->capacity = capacity;
    stack->top = -1;
    stack->arr = (int*) malloc(sizeof(stack->capacity * sizeof(int)));
    return stack;
}

I'm using this function to free the memory, but the program crashes here. 我正在使用此功能释放内存,但程序崩溃了。

// I have a problem here.
void stack_free(_Stack* stack)
{
    free(stack->arr);
    free(stack);
}

这是错误消息

Change this: 改变这个:

stack->arr = (int*) malloc(sizeof(stack->capacity * sizeof(int)));

to this: 对此:

stack->arr = (int*) malloc(stack->capacity * sizeof(int));

since you want the size of the array to be equal to stack->capacity * sizeof(int) , and not equal to the size of that expression. 因为您希望数组的大小等于stack->capacity * sizeof(int) ,并且不等于该表达式的大小。

Your program must have invoked Undefined Behavior somewhere in code not shown in the question (because of the wrong size malloc'ed), that's why it crashes later. 你的程序必须在问题中未显示的代码中调用未定义的行为(因为malloc的大小错误),这就是为什么它会在以后崩溃的原因。


PS: Since you use C++, consider using new instead (and delete , instead of free() ). PS:因为你使用C ++,考虑使用new而不是(和delete ,而不是free() )。

sizeof(stack->capacity * sizeof(int)) in your call to malloc is wrong. 在调用malloc时, sizeof(stack->capacity * sizeof(int))是错误的。 Instead of the size of the array, it gives the size of the number used to represent the size of the array. 它不是数组的大小,而是给出用于表示数组大小的数字的大小。 You probably want stack->capacity * sizeof(int) . 您可能需要stack->capacity * sizeof(int)

Another possible problem is that in C you should not cast the return value of malloc, since it can hide other mistakes and cause a crash. 另一个可能的问题是在C中你不应该转换malloc的返回值,因为它可以隐藏其他错误并导致崩溃。 See Do I cast the result of malloc? 请参阅我是否转换了malloc的结果? In C++ you will have to do it, because of the stricter type checking in C++, but it can still hide problems. 在C ++中你必须这样做,因为在C ++中进行了更严格的类型检查,但它仍然可以隐藏问题。

These are the problems I see with the code you have shown. 这些是我在您显示的代码中看到的问题。 However, remember that errors in malloc and free are not necessarily caused by the actual line where they are detected. 但是,请记住,malloc和free中的错误不一定是由检测到它们的实际行引起的。 If some part of your program damages the malloc system's internal data structures, for example by a buffer overrun, the problem can manifest in a much later call to malloc or free, in a completely different part of the program. 如果程序的某些部分损坏了malloc系统的内部数据结构,例如缓冲区溢出,那么问题可能会在稍后调用malloc或free,在程序的完全不同的部分中出现。

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

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