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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With