简体   繁体   中英

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 pointer s? Is it undefined behaviour? would like to know!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM