Search code examples
cstringserializationtextmemcpy

when I remove the "int e = 0;" I get seg fault


I have the following program in c, when I remove the "int e = 0;" I get seg fault, anyone knows why? it's not even being used?

The second thing is what is the best method here to get the first 3 int? I'm using memcpy but it's not working correctly for the first one.

#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();
}

output is below when "int e = 0;" is present

0
233
1
test

output is below when "int e = 0;" is commented

0
233
1
Segmentation fault (core dumped)

Solution

  • You're passing zero, then sizeof (length), then 2* sizeof(length) as the third argument of memcpy. That's probably not what you intended, and the last one is too large for your destination.

    Use sizeof (int1), sizeof (int2), sizeof (int3) instead of length (which is actually an offset not a length) and your problem should go away.


    Note, as Floris pointed out, you'd then have another problem since %s in a printf format specifier looks for a terminating NUL byte and you don't have one.