C 结构:分段错误
关于结构的简单问题:
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);
}
我得到这个输出
Number 12345
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的问题是您直接从文件中读入结构,而不检查结构对齐。改为这样做:
Your problem is you're directly reading into a struct from the file, without checking struct alignment. Do this instead:
我怀疑您正在读取的文件数据没有以
NUL
('\0'
) 字符终止字符串。根据 C 标准库的printf()
所遵循的字符串的 C 定义,字符串必须以NUL
字符终止。您可能会始终(通过代码)确保
.string[11] = '\0'
。或者,声明
string[13]
并确保string[12] = '\0'
另外,另一位发帖者提到了结构成员对齐问题。这是您也必须解决的一个合理的担忧。
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, whichprintf()
of the C standard library abides, a string must be terminated with aNUL
character.You might be well-off to always (via code) ensure that
.string[11] = '\0'
.OR, declare
string[13]
and ensure thatstring[12] = '\0'
Also, another poster mentioned struct member alignment concerns. That is a valid concern you must also address.
我猜测该字符串在文件中不是以空值终止的,并且您的代码也没有执行任何以空值终止的操作。
或者修改文件,使字符串以空字节结尾。
I'm guessing the string is not null-terminated in the file, and your code does nothing to null-terminate the string either.
Or modify the file so the string ends with a null byte.
你会得到缓冲区溢出。您的字符串包含 12 个字符,但没有空间用于终止
'\0'
。如果您这样做:
那就可以解决问题。
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:
That would fix the issue.