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

时间:2019-06-11 13:57:13

标签: c struct valgrind memcpy

在运行Valgrind检查时,出现“大小为8的无效读数”,这表明使用了memcpy。目标字段是一个空的,未初始化的结构。源是相同的结构,是另一个结构的成员。

即目标=柱,源= Foo->柱。

我假设问题出在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

1 个答案:

答案 0 :(得分:1)

valgrind消息提示:

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

由于程序尚未覆盖该数据,因此您有可能在运行程序时仍获得有效结果。