使char *指向另一个字符串文字泄漏内存吗?

时间:2017-02-14 09:48:23

标签: c string memory-leaks c-strings string-literals

我对这个简单的例子有一些误解:

char *s = "abc";
s = "def";

第二个字符串的赋值会导致内存泄漏,还是会被正确替换?如果前者是真的,我该如何以正确的方式替换s的值?

3 个答案:

答案 0 :(得分:6)

没有。没有内存泄漏。

您只需将s更改为指向不同的字符串文字即可(使用此s = "def";)。

简单地说,如果您没有使用malloc / calloc / realloc或任何返回动态分配内存的函数分配任何内容(文档会告诉您{{1例如,POSIX的getline()函数就是这样做的,你不需要free()

答案 1 :(得分:3)

两个字符串都是静态定义的,因此没有内存泄漏。泄漏会是什么:

Step 1:
File scrFile=null;
String path1 = null;
BufferedImage originalImage=null;
BufferedImage resizedImage=null;
System.out.println("Starting\n\n\n\n");
scrFile = ((TakesScreenshot) appiumDriver).getScreenshotAs(OutputType.FILE);
System.out.println("after scrfile\n\n\n\n");
originalImage = ImageIO.read(scrFile);
System.out.println("after originalFile\n\n\n");
BufferedImage.TYPE_INT_ARGB : originalImage.getType();
resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
Step 2: 
BufferedImage pathforToast= original image;
Step 3:
System.setProperty("jna.library.path","C:/Users/Dell/workspace/MOBILEFRAMEWORK/dlls/x64/");
Tesseract instance = Tesseract.getInstance();
`enter code here`ImageIO.scanForPlugins();
String result=null;
result = instance.doOCR(pathforToast);`enter code here`
System.out.println(result);`enter code here`

实际上有一个小的静态内存浪费(不会称之为泄漏),因为您再也无法使用char *s = strdup("abc"); // dynamic memory allocation s = "def";

但是,即使通过调用代码所在的例程也无法重复,我绝对不会称之为泄密。

现在,如果你有"abc"(数组,而不是指针)和一个大小相同的char s[] = "abc";字符串,你可以这样做:

"def"

替换字符串的内容(但不要在静态分配的指针上执行此操作,如定义代码:未定义的行为)。

答案 2 :(得分:0)

您的代码段:

char *s = "abc";
s = "def";

不会导致内存泄漏。 char *s是内存中的指针。使用char *s = "abc"时,您可以设置*s可指向的字符串文字。当您将s设置为字符串文字"def"时,您所做的就是更改*s指向的位置。

注意:您只能使用指针数组执行此操作。如果您想使用数组,则可能需要使用strcpy(3) / strncpy(3)

由于您没有使用malloc(3) / strdup(3)分配任何指针,因此很难获得内存泄漏。

但是,这是一个内存泄漏的例子:

const char *str1 = "abc";
const char *str2 = "def";

char *s1 = malloc(strlen(str1)+1); /* dynamic memory allocation with malloc() */
char *s2 = malloc(strlen(str2)+1);

s1 = s2;

在此,您将s1设置为s2。因此,这意味着s1的内存位置不再存在,因为s1指向s2,而不是它分配的原始内存位置。您无法再使用free(3)处理此指针,因为它们不再是对其位置的引用。如果你永远不会free()在堆上分配指针,那么也会导致内存泄漏。