Free () without malloc or calloc

quick question

Can you use the free () function without calling malloc first ??

e.

void someFunc( void )
{
   char str[6] = {"Hello"};

   //some processing here ....

   free(str);
}

I cannot compile errors, but does this work or is everything correct?

Thank,

+3
source share
5 answers

This is not entirely correct:

  • You cannot free a static array, for example char str[6].
  • free () should only be called in allocated memory (or in NULL).
+9
source

malloc() , . , . , , . str, stack , , .

+5

non-malloc'd Segfault. :

#include <stdlib.h>

int main()
{
  char str[6] = {"Hello"};
  free(str);
}

$gcc test.c -o test

$./test

+3

free() , . , malloc() calloc(), , , .

, undefined. , . .

, . . , , , malloc() void * free() void *; , , . , , - , . , ; , , , valgrind, , .

+2
source

No


The function free(3)takes a parameter void *, so you can pass it any pointer without a compile-time error. But bad things will happen if the pointer was not originally returned malloc(3)and never previously returned to free(3).

0
source

Source: https://habr.com/ru/post/1773335/


All Articles