c – What does pointer being freed was not allocated mean exactly?

c – What does pointer being freed was not allocated mean exactly?

Only pointers returned by calls to malloc(), realloc() or calloc() can be passed to free() (dynamically allocated memory on the heap). From section The free function of C99 standard:

The free function causes the space pointed to by ptr to be deallocated, that is, made
available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if
the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc,
the behavior is undefined.

In the posted code, str is not dynamically allocated but is allocated on the stack and is automatically released when it goes out of scope and does not need to be free()d.

Be careful. This code shows confusion about two things:

  1. The difference between stack and heap memory
  2. The operation of strcpy

Point 1

This has already been answered in a way, but Ill expand a little:

The heap is where dynamic memory is given to your process. When you call malloc (and related functions), memory is returned on the heap. You must free this memory when you are done with it.

The stack is part of your processs running state. It is where ordinary variables are stored. When you call a function, its variables are pushed onto the stack and popped back off automatically when the function exits. Your str variable is an example of something that is on the stack.

Point 2

Id like to know what that c member of your matrix array is. If it is a pointer, then you might be confused about what strcpy does. The function only copies bytes of a string from one part of memory to another. So the memory has to be available.

If c is a char array (with sufficient number of elements to hold the string), this is okay. But if c is a pointer, you must have allocated memory for it already if you want to use strcpy. There is an alternative function strdup which allocates enough memory for a string, copies it, and returns a pointer. You are responsible for freeing that pointer when you no longer need it.

c – What does pointer being freed was not allocated mean exactly?

It used free without using malloc. You cant release memory that hasnt been allocated.

Leave a Reply

Your email address will not be published.