Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free() function without malloc or calloc

Tags:

c

malloc

calloc

quick question

Can you use the free() function without having to prior call a malloc ??

ei.

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

   //some processing here ....

   free(str);
}

I get no compiling errors but Does this work or is it correct at all ?

Thank you,

like image 938
jramirez Avatar asked Nov 30 '22 17:11

jramirez


2 Answers

This is not at all correct:

  1. You cannot free a static array such as char str[6].
  2. free() should only be called on memory you allocated (or on NULL).
like image 193
Zabba Avatar answered Dec 15 '22 15:12

Zabba


When you call malloc() or any other allocation function, memory will be allocated on the heap. This is the only memory that can be freed. When you declare a static string, as you've done in your example, the string is allocated at compile time in another memory segment. The same goes for the str pointer itself which is allocated on the stack, and thus cannot be freed either.

like image 41
Emil H Avatar answered Dec 15 '22 15:12

Emil H