Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does setting a string char to null cause a memory leak in C?

This seems like a silly question, but I couldn’t find the answer.

Anyways, if you set an arbitrary character to null in a string,
then free the string, does that cause a memory leak?

I suppose my knowledge of how the free function works is limited.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/*
     char *
     strchr(const char *s, int c);

     char *
     strrchr(const char *s, int c);

     The strchr() function locates the first occurrence of c (converted to a
     char) in the string pointed to by s.  The terminating null character is
     considered part of the string; therefore if c is ‘\0’, the functions
     locate the terminating ‘\0’.

     The strrchr() function is identical to strchr() except it locates the
     last occurrence of c.
*/

char* string = strdup ("THIS IS, A STRING WITH, COMMAS!");

char* ch = strrchr( string, ',' );
*ch = 0;

free( string );

/*
    The resulting string should be: "THIS IS, A STRING WITH"
    When the string pointer is freed, does this result in a memory leak?
*/

>Solution :

Not a stupid question in my opinion.
TLDR: no you do not cause a memory leak.

Now the longer answer: free has no idea what a string is. If you pass it a char* or an int* it could not care less.

The way malloc and free works is the following: when you call malloc you supply a size and receive a pointer with the promise of that many bytes being reserved on the heap from the position of the pointer onwards. However at that point the size and position are also saved internally in some way (this depends and is an implementation detail).
Now when you call free it does not need to know the size, it can just remove the entry your pointer belongs to together with the size

Addendum: also not every char* is a string, it just so happens that "abcd" becomes a null terminated char* pointing to the 'a', but a char* itself points to a single char, not multiple

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading