xSuperMu
xSuperMu

Reputation: 474

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

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);
}

Here's the error message

Upvotes: 4

Views: 1427

Answers (2)

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

sizeof(stack->capacity * sizeof(int)) in your call to malloc is wrong. 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).

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. See Do I cast the result of malloc? In C++ you will have to do it, because of the stricter type checking in C++, but it can still hide problems.

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. 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.

Upvotes: 2

gsamaras
gsamaras

Reputation: 73366

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.

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.


PS: Since you use C++, consider using new instead (and delete, instead of free()).

Upvotes: 3

Related Questions