我在c中有以下程序,当我删除“int e = 0;”我得到段故障,谁知道为什么?它甚至没有被使用?
第二件事是获得前3个int的最佳方法是什么?我正在使用memcpy,但它对第一个没有正常工作。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int test()
{
unsigned char string1[] = {0xce,0x01,0x00,0x00,0xe9,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x74,0x65,0x73,0x74};
//0xce,0x01,0x00,0x00 this should be the first int
//0xe9,0x00,0x00,0x00 Second int
//0x01,0x00,0x00,0x00 third int, the rest is the text "test"
int e = 0;// when I comment this one I get Segmentation fault
unsigned int int1 = 0;
unsigned int int2 = 0;
unsigned int int3 = 0;
int length = 0;
int size = 0;
size = sizeof(length);
memcpy(&int1, string1, length); printf("%d\n",int1); //should be 461
length += size;
memcpy(&int2, &string1[length], length); printf("%d\n",int2); //shoud be 233
length += size;
memcpy(&int3, &string1[length], length); printf("%d\n",int3); //should be 1
length += size;
printf("%s\n",&string1[length]);//text should be test
}
int main()
{
test();
}
当“int e = 0;”时,输出低于在场
0
233
1
test
当“int e = 0;”时,输出低于被评论
0
233
1
Segmentation fault (core dumped)
答案 0 :(得分:3)
您传递零,然后sizeof (length)
,然后2* sizeof(length)
作为memcpy
的第三个参数。这可能不是你想要的,最后一个对你的目的地来说太大了。
使用sizeof (int1)
,sizeof (int2)
,sizeof (int3)
代替length
(这实际上是偏移而非长度),您的问题应该消失。
请注意,正如Floris指出的那样,你会遇到另一个问题,因为printf格式说明符中的%s
会查找终止的NUL字节而你没有。
答案 1 :(得分:2)
您需要对字符串进行null终止。当你声明e
它恰好占用了字符串后面的内存中的一个点,并为你提供了空终止。你需要添加'\0'
作为传入的字符串中的最后一个值,一切都会很好......
答案 2 :(得分:0)
内存溢出:
printf("%s\n",&string1[length])
您的字符串未正确终止\ 0。 e = 0终止你的字符串。
此外,您使用的是长度而不是大小。
应该是:
int test() { unsigned char string1[] = {0xce,0x01,0x00,0x00,0xe9,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x74,0x65,0x73,0x74, 0x00}; //0xce,0x01,0x00,0x00 this should be the first int //0xe9,0x00,0x00,0x00 Second int //0x01,0x00,0x00,0x00 third int, the rest is the text "test" int e = 0;// when I comment this one I get Segmentation fault unsigned int int1 = 0; unsigned int int2 = 0; unsigned int int3 = 0; int length = 0; int size = 0; size = sizeof(unsigned int); memcpy(&int1, string1, size); printf("%d\n",int1); //should be 461 length += size; memcpy(&int2, &string1[length], size); printf("%d\n",int2); //shoud be 233 length += size; memcpy(&int3, &string1[length], size); printf("%d\n",int3); //should be 1 length += size; printf("%s\n",&string1[length]);//text should be test }
请注意string1上的0x00
终止以及在memcpy中使用size而不是length。