简体   繁体   English

使用指针算法进行迭代,是否可能发生内存泄漏?

[英]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); 如果我尝试free(ptr); I allocated with malloc it'll throw me an exception. 我用malloc分配它会抛出异常。

Is there an memory leak going on? 是否存在内存泄漏? can't I free it because it's empty? 因为它是空的,我不能释放它吗? has it something todo with null pointer s? null pointer s有关系吗? Is it undefined behaviour? 它是不确定的行为吗? would like to know! 想知道!

With ++ptr; 使用++ptr; , you have lost the pointer returned by malloc() . ,则丢失malloc()返回的指针。 Unless you pass the exact pointer returned by the memory allocator functions to free() , you'll invoke undefined behavior . 除非将内存分配器函数返回的确切指针传递给free() ,否则将调用未定义的行为

Solution: You need to keep a copy of the actual returned pointer somewhere to be passed to free() later. 解决方案:您需要在某个地方保留实际返回的指针的副本,以便以后传递给free()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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