[英]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.我怀疑您正在读取的文件数据不会以NUL
( '\\0'
) 字符终止字符串。 By the C definition of strings, which printf()
of the C standard library abides, a string must be terminated with a NUL
character.根据 C 标准库的printf()
所遵循的 C 字符串定义,字符串必须以NUL
字符终止。
You might be well-off to always (via code) ensure that .string[11] = '\\0'
.您可能总是(通过代码)确保.string[11] = '\\0'
。
OR, declare string[13]
and ensure that string[12] = '\\0'
或者,声明string[13]
并确保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'
.您的字符串包含 12 个字符,但您没有空间用于终止'\\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.或者修改文件,使字符串以空字节结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.