Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free dynamically allocated memory

Tags:

c

free

int i;
char *s = (char*)malloc(sizeof(char)*10);
for(i = 0; i <= 4; ++i)
    s[i] = 'a';
s[5] = '\0';
printf("%s\n", s);
free(s).

Will the above code have memory leak problem? How does the function "free" know how many memory need to be freed?

like image 823
Fihop Avatar asked Apr 25 '26 15:04

Fihop


1 Answers

There is no memory leak in your code. As to your second question, when you call malloc, more happens than just returning memory to you. The C library reserves some space to put its own headers and bookkeeping information so that when you call free it can do the right thing.

Some editorial notes about your code:

  • you don't need to cast the return value of malloc() in a C program. Conversions between void * (which malloc() returns) and other pointer types are implicit in C.

  • sizeof(char) is 1, why bother writing it out?

  • your loop writes three characters into s, and then your program skips a character (s[4]) before adding the \0. That's a bit weird. Did you mean to use i <= 4 in your loop, or maybe s[4] = '\0' after it?

  • you have a . rather than a ; after your free() call. I guess that's just a typo here, rather than in your program, since it won't compile that way, though.

like image 196
Carl Norum Avatar answered Apr 28 '26 10:04

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!