c++ - valgrind 发现错误将指针传递给函数,但当代码在同一范围内时没有错误

标签 c++ pointers valgrind

我想知道为什么在此示例代码中,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/

相关文章:

c++ - 指向函数的指针的初始化数组

c++ - 多维动态数组,为什么不起作用?

c++ - qt designer 指定的 QDialog 的 valgrind 问题

链表中的C内存泄漏

c++ - 是否可以将非枚举值作为枚举函数参数传递?

c++ - 如何使用可变参数包为嵌套模板类起别名

c++ - 前缀运算符重载

c - int 指针指向 void 指针,以某种方式指向 char 数组?

c++ - 类似单例的管理类,更好的设计吗?

c - 由于 getaddrinfo() 导致 Valgrind 内存泄漏