当运行Valgrind检查时,我得到一个“8号无效读取”,它指向memcpy的使用。目标字段是一个空的未初始化结构。源是同一个结构,它是另一个结构的成员。
即目的地=Bar,源=Foo->Bar。
我认为问题在于memcpy中的大小arg。我试过使用sizeof(Foo->Bar)、sizeof(Bar)和sizeof(Bar)。
在标题中:

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));

我得到了预期的表现,但瓦尔格林似乎不喜欢这样做。
错误如下:
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试图读取的数据已经无效
偶然的机会,你仍然得到有效的结果时,运行该程序,因为没有任何东西已经覆盖了该数据。

10-02 02:19
查看更多