简体   繁体   中英

free dynamically allocated memory

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.

It will not leak. The library knows how much to free because it internally keeps track of the allocated size of every block. The exact way it does that is an implementation detail that may change from malloc to malloc even from release to release and you should not be concerned with it.

No, you free s at the end and you don't use more than s. I'd say you're ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM