简体   繁体   English

初始化字符串时发生内存泄漏

[英]Memory leak when initialise string

Case 1 : I have written following c program and when I checked for memory leak I got memory leakage at this line str = (char*)malloc(10); 情况1:我编写了以下c程序,当我检查内存泄漏时,在此行出现了内存泄漏str = (char*)malloc(10); even when I have written statement to free that memory 即使我写了声明以释放该记忆

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *str;
    str = (char*)malloc(10);
    str = "string";
    printf("length : %ld\n",strlen(str));
    free(str);
    return 0;
}

Case 2: 情况2:

When I replaced str="string" with strcpy() there is no any leak why it is so? 当我将str="string"替换为strcpy() ,为什么没有泄漏?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *str;
    str = (char*)malloc(10);
    strcpy(str,"string");
    printf("length : %ld\n",strlen(str));
    free(str);
    return 0;
}

str = "string";

After this str points to different memory location(on many platforms it will be read only memory). str指向不同的内存位置后(在许多平台上它将是只读内存)。 So it no longer points to memory that you allocated via malloc . 因此,它不再指向通过malloc分配的malloc When you call free(str) you are trying to free some memory that you aren't suppose to. 当您调用free(str)您试图释放一些您不应该拥有的内存。 This is an undefined behavior. 这是未定义的行为。 It may do nothing, or it may crash. 它可能什么也不做,或者可能崩溃。 And the malloced memory is being leaked. 并且分配的内存正在泄漏。

strcpy(str,"string");

Here the string is copied to already allocated memory pointed by str . 在这里,字符串被复制到str指向的已分配内存中。 You own this memory, you copied data to it and then you free it. 您拥有此内存,将数据复制到其中,然后释放它。 So there is no problem here. 因此,这里没有问题。

So the basic difference between the two cases is that in first case str points to a different location than the allocated one. 因此,这两种情况之间的基本区别在于,在第一种情况下, str指向的位置与分配的位置不同。

Both are not same. 两者都不一样。

In this case, strcpy(str, "string") is correct way to copy the "string" to str. 在这种情况下, strcpy(str, "string")是将“ string”复制到str的正确方法。 str is allocated then you free it. str被分配,然后您将其释放。 so no memory is leaking. 因此没有内存泄漏。

In case of str = "string" , memory allocated to str will lost and it will cause memory leak. 如果str = "string" ,分配给str的内存将丢失并且将导致内存泄漏。

 str = (char*)malloc(10);
 str = "string"; <-- You just lost the pointer to the malloced memory. ie. memory leak.
 free(str); <-- Here you are trying to free the `"string"` itself. Not possible.

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

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