c - “大小 8 的无效读取”- Valgrind。尝试用来自其他结构的数据填充结构

标签 c struct valgrind memcpy

运行 Valgrind 检查时,我收到“大小 8 的无效读取”,这表明使用了 memcpy。目标字段是一个空的、未初始化的结构。源是同一个结构,它是另一个结构的成员。

即 Destination = Bar,Source = Foo->Bar。

我假设问题在于 memcpy 中的大小 arg。我尝试过使用 sizeof(Foo->Bar)、sizeof(Bar) 和 sizeof(Bar_s)。

在标题中:

struct Foo_s
{
  Bar_t payload;
  //other structs and variables
};

typedef struct
{
    uint64_t timestamp;
    uint16_t id;
} Bar_t;

在c文件中:

//Foo_s is passed into the function already populated, let's call it foo_data
Bar_t payload_data;

memcpy(&payload_data, &(foo_data->payload_data), sizeof(foo_data->payload_data));

我得到了预期的行为,但 Valgrind 似乎不喜欢它的完成方式。

这里是错误:

Thread 36 function_name:47/101:
==774== Invalid read of size 8
==774==    at 0x1C1E59: function_name (in /path/to/exe)
==774==    by 0x189065: another_function (in /path/to/exe)
==774==    by 0x5D544A3: another_function2 (pthread_create.c:456)
==774==  Address 0x40bb6b8 is on thread 11's stack
==774==  1896 bytes below stack pointer

最佳答案

valgrind 消息表明:

  • 在线程 11 中,您将 Foo_s 创建为局部变量,即在堆栈上
  • 你启动了一个新线程,线程 36,传递了一个指向该变量的指针
  • 线程 36 尝试从该指针读取数据
  • 但是线程 11 已经“离开”了您创建变量的函数,因此线程 36 尝试读取的数据已经无效

运行程序时您仍然得到有效结果的机会是因为尚未覆盖该数据。

关于c - “大小 8 的无效读取”- Valgrind。尝试用来自其他结构的数据填充结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56545436/

相关文章:

c - 选择排序——稳定

c++ - 如何在 Linux 应用程序上使用 C++ 中的终端输入中断循环/进程

c - __u8 __s16 等的新版本

c - sizeof 作为字符串维度的段错误

c - lstat() st_blocks 输出错误值

c - malloc 和 realloc 的问题

java - Valgrind 和 Java

c - getline() 有内存泄漏,用 valgrind 测试

swift - 用变量填充结构

go - 如何使用 reflect.Type 对 switch 进行断言