Search code examples
cloopsmemory-leaksfreedynamic-memory-allocation

using pointer arithmetic to iterate, possible memory leak?


I'm currently using the following code to get an "lowered" string:

void strlower(char** string)
{
    char* ptr = malloc((strlen(*string)+1) * sizeof **string);
    memcpy(ptr, *string, (strlen(*string)+1) * sizeof **string);

    while (*ptr) {
        if (*(ptr) >= 'A' && *(ptr) <= 'Z') {
            memset(*string + (strlen(*string) - strlen(ptr)), (char)(*(ptr)+32), sizeof **string);
        }
        ++ptr;
    }
    memcpy(*string, ptr, (strlen(*string) +1) * sizeof **string);  

    /// free(ptr); THROWS ERROR
    free(ptr);
    ptr = NULL;
}

If I try to free(ptr); I allocated with malloc it'll throw me an exception.

Is there an memory leak going on? can't I free it because it's empty? has it something todo with null pointers? Is it undefined behaviour? would like to know!


Solution

  • With ++ptr;, you have lost the pointer returned by malloc(). Unless you pass the exact pointer returned by the memory allocator functions to free(), you'll invoke undefined behavior.

    Solution: You need to keep a copy of the actual returned pointer somewhere to be passed to free() later.