Fihop
Fihop

Reputation: 3177

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?

Upvotes: 3

Views: 1198

Answers (3)

Carl Norum
Carl Norum

Reputation: 224844

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.

Upvotes: 4

Nik Bougalis
Nik Bougalis

Reputation: 10613

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.

Upvotes: 2

DWright
DWright

Reputation: 9500

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

Upvotes: 0

Related Questions