Search code examples
pointersmemorymemory-leakscharacteransi-c

Does continous reassigning of character strings lead to memory leak?


I have two questions:

Q1. The character pointers are used to point to a location where a given string is stored. If we keep reassigning the string, does it lead to memory leak?

On a Linux system I see:

$ cat chk.c
#include <stdio.h>

#define VP (void *)

int main()
{
        char *str;

        str = "ABC";
        printf("str = %p points to %s\n", VP str, str);

        str = "CBA";
        printf("str = %p points to %s\n", VP str, str);

        return 0;
}

$ cc chk.c && ./a.out
str = 0x8048490 points to ABC
str = 0x80484ab points to CBA
$

Q2. What is the maximum length of a string that can be assigned as above?


Solution

  • Can your sample code memory leak? No. You are assigning constant strings already in your program so no extra memory allocation happens.

    Memory leaks are from forgotten malloc() type calls, or calls that internally do mallocs() type operations that you may not be aware of. Beware of functions that return a pointer to memory... such as strdup(). Such tend to either be not be thread safe or leak memory, if not both. Better are functions like snprintf() where the caller provides both a memory buffer and a maximum size. These function's don't leak.

    Maximum string length: tends to have no artificial limit except available memory. Memory in the stack may be limited by various constraints (char can_be_too_big[1_000_000]), but memory from malloc() is not. Malloc memory ias a question of how much free memory you have (char * ok = malloc(1_000_000). Your local size_t provides the maximum memory to allocate in theory, but in practice it is much smaller.