我在一个共享内存段中有一个结构,我正在尝试使用memcpy在我的结构中到达一个二维数组。
struct shared_mem_struct{
int proc_id;
int flag[21];
int turn;
char bounded_buffer[5][200];
};我试图用memcpy访问bounded_buffer,但我总是收到垃圾信息。
memcpy(shared_mem->bounded_buffer[z], "empty", sizeof(shared_mem));我已经阅读了memcpy的文档,但我对一个有效的解决方案一无所获。我也尝试过:
memcpy(shared_mem->bounded_buffer[z], "empty", sizeof(shared_mem->bounded_buffer[index));我能够在所有的fork中读写,所以访问共享内存不是问题。
发布于 2018-02-17 14:40:06
因为你做错了什么。
memcpy(shared_mem->bounded_buffer[z], "empty", sizeof(shared_mem));应该是
memcpy(shared_mem->bounded_buffer[z], "empty", strlen("empty")+1);因为它不是您想要复制的字符的缓冲区字节大小,而是您想要从"empty"复制这些字母。这就是为什么长度应该是1的原因。
在本例中,您访问的内存超出了字符串文字的范围。那是undefined behavior。
https://stackoverflow.com/questions/48838689
复制相似问题