问题
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 :)
回答1:
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);
回答2:
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.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/5983089/c-structs-segmentation-fault