Search code examples
cmemory-managementcalloc

c - successive calloc calls corrupt some memory


The code looks something like:

char *global1 = NULL;
char *global2 = NULL;
char *global3 = NULL;
char *global4 = NULL;

void func2(char *gPtr, char **gPtrToInitialize)
{
    if(*gPtrToInitialize == NULL)                     // Here, gPtr is correct
    {
        *gPtrToInitialize = dlcalloc(MAX_PATH, 1);      
    }                              // Here, gPtr has trailing junk characters

    // Do some initialization
}

void func1()
{
    if(global1 == NULL)
    {
        global1 = dlcalloc(MAX_PATH, 1);
    }
    func2(global1, &global2);
    func2(global1, &global3);
    func2(global1, &global4);

    // Do other tasks

    // Free all allocated global variables
}

Note: In the above code, dlcalloc refers to code defined in Doug Lea's malloc.c.


Before the calloc inside func2(),

gPtr = "C:\Program Files\Test\Path.txt"

After the calloc inside func2(),

gPtr = "C:\Program Files\Test\Path.txt♂"


My question is, do successive dlcalloc() calls have a small chance of corrupting some other variable's memory? The above code is a generalization of a part of a large code base for something I'm working on.


Solution

  • Okay guys I just solved my problem. This was what was happening in func2():

    • gPtr pointed to 0x009b0038.
    • strlen("C:\Program Files\Test\Path.txt") = 30 bytes.
    • *gPtrToInitialize on allocation pointed to 0x009b0057 which starts exactly after gPtr's section ends.
    • Since the string pointed to by gPtr doesn't have a trailing '\0', any string operation on gPtr actually went into *gPtrToInitialize's memory too.

    All this was solved when I simply added a trailing '\0'.

    Thanks for all your answers!