简体   繁体   中英

C structs: segmentation fault

Quick question about structs:

struct xint {
     int number;
     char string[12];
};

int main(int argc, char *argv[])
{
  struct xint offsets, *poffsets;
  poffsets=&offsets;
  FILE * pFile = fopen("file","rb");
  fread(poffsets,1,16,pFile);
  printf("Number %d\nString %s\n",offsets.number,offsets.string);
}

I get this output

Number 12345
Segmentation fault

I know I've probably done something wrong with structures and pointers and memory allocation. Thanks in advance :)

Your problem is you're directly reading into a struct from the file, without checking struct alignment. Do this instead:

  fread(&offset.number,1,sizeof(offsets.number),pFile);
  fread(&offset.string,1,sizeof(offsets.string),pFile);

I suspect that the file data you are reading does not terminate the string with a NUL ( '\\0' ) character. By the C definition of strings, which printf() of the C standard library abides, a string must be terminated with a NUL character.

You might be well-off to always (via code) ensure that .string[11] = '\\0' .

OR, declare string[13] and ensure that string[12] = '\\0'

Also, another poster mentioned struct member alignment concerns. That is a valid concern you must also address.

You get buffer overflow. Your string is made to contain 12 chars, but you don't have space for a terminating '\\0' .

If you did:

struct xint {
     int number;
     char string[16]; // Make sure you have enough space for the string + '\0'.
};

int main(int argc, char *argv[])
{
    struct xint offsets, *poffsets;

    // Initialize your memory to 0. This will ensure your string is 
    // '\0'-terminated.
    // FYI, sizeof(xint) here is 20.
    memset(&offsets, 0, sizeof(xint)); 

    poffsets=&offsets;
    FILE * pFile = fopen("file","rb");
    fread(poffsets,1,16,pFile);
    fclose(pFile);
    printf("Number %d\nString %s\n",offsets.number,offsets.string);
}

That would fix the issue.

I'm guessing the string is not null-terminated in the file, and your code does nothing to null-terminate the string either.

fread(poffsets, 1, 16, pFile);
offsets.string[11] = '\0';
printf("Number %d\nString %s\n", offsets.number, offsets.string);

Or modify the file so the string ends with a null byte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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