我想知道为什么在此示例代码中,valgrind 没有发现任何错误或丢失的内存:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;
/* Initial memory allocation */
str = (char *) malloc(8);
strcpy(str, "example");
printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 14);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
但是,当我用函数替换这些行时:
int main() {
...
/* Reallocating memory */
newstr(str);
...
}
void newstr(char *str) {
str = (char *) realloc(str, 14);
strcat(str, ".com");
}
我在 valgrind 上收到 19 个错误,主要是关于无效读取的提示。然而,程序执行和输出的一切都是一样的,没有错误。当我将 str
传递到 valgrind 通知我的内存中发生的函数时,是否发生了什么?我该怎么做才能解决这个问题?我如何才能更多地了解这种行为及其影响?
这是两种情况下程序的输出:
String = example, Address = 16445456
String = example.com, Address = 16445456
最佳答案
作为一般规则,传递给 C 函数的参数按值传递。除非您显式地通过引用传递,或者传递一个指向您的对象的指针,否则在函数返回时,在被调用函数中所做的更改将不会保留。
在您的情况下,您可能正在传递一个指针,但您正试图修改函数中的指针,而不是修改指针引用的内容。
除了在返回新指针的其他答案中提供的解决方案外,您还有两个选择:
指向指针的指针
void newstr(char **str) {
*str = (char *) realloc(*str, 25);
strcat(*str, ".com");
}
引用
void newstr(char *&str) {
str = (char *) realloc(str, 25);
strcat(str, ".com");
}
关于c++ - valgrind 发现错误将指针传递给函数,但当代码在同一范围内时没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099199/