Home > Software design >  Does setting a string char to null cause a memory leak in C?
Does setting a string char to null cause a memory leak in C?

Time:08-24

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.

/*
     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?
*/

CodePudding user response:

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* points to 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

CodePudding user response:

malloc only allocates the chunk of memory and gives you the reference to it. If you do not read or write outside the boundaries of this chunk you can do whatever you want with it.

  • Related