Pergunta

Using c:

  char ptr[n];
  free(ptr);

In my opinion: when "char ptr[n];" is used, the memory is allocated, and ptr is pointed to it, free(ptr) should work. And the program failed, why?(n == 5 e.g.) Any deep analysis?

Foi útil?

Solução

Because you called free on a variable not allocated with malloc.
This causes Undefined Behavior. Luckily for you it crashes and you can detect it, else it can crash at most awkward times.

You call free for deallocating memory of heap allocated variables, What you have is an array on local storage(assuming it to be in a function) and it automatically deallocates when the scope({,}) in which it was created ends.

Outras dicas

Because this is undefined behavior what you're doing. (It means it can literally can do anything, including crashing, running seemingly fine, making daemons fly out of your nose, etc.) You can only free() a pointer that you acquired using malloc().

Auto arrays do not have to be free()'d. They are deallocated when their scope ends.

Only free an object that has been allocated by malloc. Freeing an object that has not been allocated by malloc is undefined behavior.

Because of `char ptr[n];' is away to declare an array in STACK memory, and it has scope of the block, which mean it destroyed from the memory when the block is finish.

but when you use malloc(size) the pointer will point to in a piece of memory in the HEAP memory and it take the scope which the programer give it. I mean that when you want to destroy it you must use free(ptr) or OS will free it after the program finish.

So, when you use free on pointer that point to a piece of memory in STACK memory it cause Undefined Behavior and the program crash, because free operates only on the HEAP memory.

This looks similar can a call to free in c ever fail(SO) The behavior is undefined as per the standard, In some cases your code would not crash so soon. It may corrupt the heap and crash very late during execution and make the debugging kind of difficult.
In a way it depends on the design of malloc/free methods.

One way which I know is : with each malloc, an extra block of memory is attached to the block which is returned by malloc(). This block contains some housekeeping data which is needed while a call to free(). In your case this data is missing since the memory was not allocated by malloc(). So free() is trying to use the data preceding your array without knowing that its junk.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top