【问题标题】:when I remove the "int e = 0;" I get seg fault当我删除“int e = 0;”我得到段错误
【发布时间】:2013-07-10 03:21:58
【问题描述】:

当我删除“int e = 0;”时,我在 c 中有以下程序我得到段错误,有人知道为什么吗?它甚至没有被使用?

第二件事是这里获得前 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)

【问题讨论】:

    标签: c string serialization text memcpy


    【解决方案1】:

    您将传递零,然后传递sizeof (length),然后传递2* sizeof(length) 作为memcpy 的第三个参数。这可能不是您想要的,最后一个对于您的目的地来说太大了。

    使用sizeof (int1)、sizeof (int2)、sizeof (int3) 而不是length(实际上是偏移量而不是长度),您的问题应该会消失。


    请注意,正如 Floris 指出的那样,您会遇到另一个问题,因为 printf 格式说明符中的 %s 会查找终止 NUL 字节而您没有。

    【讨论】:

    • 更详细地说,额外的 int 声明在堆栈上提供了足够的安全空间,以便您安全地超越它。
    • @Curt:在他的特定测试中确实如此,但当然不能保证堆栈布局。
    • @BenVoigt 你错过了最后一个 printf,这无论如何都会导致错误,但是是的,取决于内存布局,它可能是其中一个。
    【解决方案2】:

    您需要以空值终止您的字符串。当您声明 e 时,它恰好在字符串之后占据内存中的一个位置,并为您提供空终止。您需要在传入的字符串中添加'\0' 作为最后一个值,一切都会好起来的...

    【讨论】:

      【解决方案3】:

      内存溢出:

      printf("%s\n",&string1[长度])

      您的字符串没有以 \0 正确终止。 e=0 终止您的字符串。

      此外,您使用的是长度而不是大小。

      应该是:

      整数测试() { unsigned char string1[] = {0xce,0x01,0x00,0x00,0xe9,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x74,0x65,0x73,0x74, 0x00}; //0xce,0x01,0x00,0x00 这应该是第一个 int //0xe9,0x00,0x00,0x00 秒 int //0x01,0x00,0x00,0x00 第三个int,剩下的就是文本“test” int e = 0;// 当我评论这个时,我得到分段错误 无符号整数 int1 = 0; 无符号整数 int2 = 0; 无符号整数 int3 = 0; 整数长度 = 0; 整数大小 = 0; 大小 = sizeof(unsigned int); memcpy(&int1, string1, 大小); printf("%d\n",int1); //应该是461 长度 += 大小; memcpy(&int2, &string1[长度], 大小); printf("%d\n",int2); //应该是233 长度 += 大小; memcpy(&int3, &string1[长度], 大小); printf("%d\n",int3); //应该是1 长度 += 大小; printf("%s\n",&string1[length]);//文本应该被测试 }

      注意 string1 上的 0x00 终止符,以及在 memcpy 中使用大小而不是长度。

      【讨论】:

        猜你喜欢
        • 2021-07-08
        • 2020-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-05
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多