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 a memory leak problem? How does the "free" function know how much memory needs to be freed?

+3


source to share


3 answers


There is no memory leak in your code. As for your second question, there malloc

is more going on in the call than just returning memory to you. The C library reserves space to place its own headers and accounting information so that when called, free

it can do the right thing.

Some editorial notes on your code:



  • you don't need to specify the return value malloc()

    in a C program. Conversions between void *

    (which it malloc()

    returns) and other pointer types are implicit in C.

  • sizeof(char)

    1

    why write it?

  • your loop writes three characters to s

    and then your program skips the character ( s[4]

    ) before adding \0

    . It's a bit strange. Did you mean to use it i <= 4

    in your loop or maybe s[4] = '\0'

    after it?

  • after the call free()

    you have .

    , not ;

    . I'm guessing it's just a typo here and not in your program as it won't compile that way.

+4


source


It won't flow. The library knows how much to free as it internally keeps track of the allocated size of each block. The exact way to do it is an implementation detail that can vary from malloc

to malloc

even from release to release, and you don't have to worry about that.



+2


source


No, you are free at the end and you don't use more than s. I would say that everything is fine.

0


source







All Articles