如何将动态分配的内存释放到结构内的数组?
How to free a dynamically allocated memory to an array inside a struct?
我正在尝试释放 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 have a problem here.
void stack_free(_Stack* stack)
{
free(stack->arr);
free(stack);
}
sizeof(stack->capacity * sizeof(int))
在你对 malloc 的调用中是错误的。它给出的不是数组的大小,而是用来表示数组大小的数字的大小。你可能想要 stack->capacity * sizeof(int)
.
另一个可能的问题是在 C 中你不应该转换 malloc 的 return 值,因为它可以隐藏其他错误并导致崩溃。参见 Do I cast the result of malloc?
在 C++ 中你将不得不这样做,因为 C++ 中的类型检查更严格,但它仍然可以隐藏问题。
这些是我在您显示的代码中看到的问题。但是,请记住 malloc 和 free 中的错误不一定是由检测到它们的实际行引起的。如果程序的某些部分损坏了 malloc 系统的内部数据结构,例如由于缓冲区溢出,问题可能会在稍后调用 malloc 或 free 时出现在程序的完全不同的部分。
改变这个:
stack->arr = (int*) malloc(sizeof(stack->capacity * sizeof(int)));
对此:
stack->arr = (int*) malloc(stack->capacity * sizeof(int));
因为您希望数组的大小等于 stack->capacity * sizeof(int)
,而不等于该表达式的大小。
您的程序一定是在问题中未显示的代码中的某处调用了未定义行为(因为错误的 malloc'ed 大小),这就是它后来崩溃的原因。
PS:由于您使用 C++,请考虑使用 new
(和 delete
,而不是 free()
)。
我正在尝试释放 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 have a problem here.
void stack_free(_Stack* stack)
{
free(stack->arr);
free(stack);
}
sizeof(stack->capacity * sizeof(int))
在你对 malloc 的调用中是错误的。它给出的不是数组的大小,而是用来表示数组大小的数字的大小。你可能想要 stack->capacity * sizeof(int)
.
另一个可能的问题是在 C 中你不应该转换 malloc 的 return 值,因为它可以隐藏其他错误并导致崩溃。参见 Do I cast the result of malloc? 在 C++ 中你将不得不这样做,因为 C++ 中的类型检查更严格,但它仍然可以隐藏问题。
这些是我在您显示的代码中看到的问题。但是,请记住 malloc 和 free 中的错误不一定是由检测到它们的实际行引起的。如果程序的某些部分损坏了 malloc 系统的内部数据结构,例如由于缓冲区溢出,问题可能会在稍后调用 malloc 或 free 时出现在程序的完全不同的部分。
改变这个:
stack->arr = (int*) malloc(sizeof(stack->capacity * sizeof(int)));
对此:
stack->arr = (int*) malloc(stack->capacity * sizeof(int));
因为您希望数组的大小等于 stack->capacity * sizeof(int)
,而不等于该表达式的大小。
您的程序一定是在问题中未显示的代码中的某处调用了未定义行为(因为错误的 malloc'ed 大小),这就是它后来崩溃的原因。
PS:由于您使用 C++,请考虑使用 new
(和 delete
,而不是 free()
)。