简体   繁体   English

C memcpy中的分割错误

[英]segmentation fault in C memcpy

I have a basic problem using memcpy and don't understand where the problem is. 我在使用memcpy时遇到一个基本问题,不知道问题出在哪里。 I show below the relevant parts of the code. 我在下面显示代码的相关部分。 The code seg. 代码段。 faults in the last right iteration of the loop. 在循环的最后一次右迭​​代中出现故障。 Why can't I index in to an memory area that is reserved? 为什么不能索引到保留的存储区?

Thank you in advance. 先感谢您。

mystr->data = malloc(2048);

unsigned char buf[8500];
for (i=0;i<32;i++){
    offset = i*256;
    memcpy(&mystr->data[64*i],&buf[8+offset],64);
}

From the comments it'cs clear that my suspicion was right: 从评论中可以明显看出我的猜想是对的:

if sizeof( *mystr->data ) > 1 (because eg it's unsigned long long *data; ) then you run beyond the end of the buffer because the offsets calculated by expressions like &mystr->data[64*i] are relative to the type, here it is mystr->data + 64*i*sizeof(*mystr->data) bytes which was up to 64*31*8 in your code. 如果sizeof( *mystr->data ) > 1 (例如,因为它是unsigned long long *data; ),那么您将超出缓冲区的末尾,因为&mystr->data[64*i]这样的表达式所计算的偏移量是相对于类型,这里是mystr->data + 64*i*sizeof(*mystr->data) bytes ,在您的代码中最大为64 * 31 * 8。

You could either change the type, as you have done, or change the offsets (to &mystr->data[8*i] in your case) depending on what what seems 'right' semantically in your context 您可以根据需要更改类型,也可以更改偏移量(在您的情况下为&mystr->data[8*i] ),具体取决于上下文中语义上“正确”的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM