gpt4 book ai didi

c - ubuntu32 位上的段错误(核心转储)

转载 作者:行者123 更新时间:2023-11-30 20:51:14 25 4
gpt4 key购买 nike

使用 gcc 编译器编译给定的程序后,我尝试在我的 ubuntu 机器上运行该程序,但收到错误消息:段错误(核心转储),但是当我编译/运行时我的 Windows 机器上的 devc++ 上的相同程序运行得很好。有什么想法吗?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int bof( char *str)
{
char buffer [24];
strcpy(buffer , str);
return 1;
}

int main (int argc , char **argv)
{
char str[517];
FILE *badfile ;
badfile = fopen (" badfile ", "r");
fread(str , sizeof(char), 517, badfile);
bof(str);
printf(" Returned properly \n");
return 1;
}

最佳答案

您正在从大小最多为 517 字节的 str 复制到大小仅为 24 字节的 buffer

因此,如果您读入的字符串长度超过 24 个字节,则您会将 buffer 的末尾复制到不属于它的内存中。即undefined behavior ,这意味着程序可能会崩溃,也可能看起来工作正常,或者可能显示其他看似随机的行为。

您需要确保不会覆盖数组的边界:

// first zero out the buffer, since strncpy doesn't necessarily NULL terminate
memset(buffer, 0 sizeof(buffer));
strncpy(buffer, str, sizeof(buffer) - 1);

编辑:

正如 iharob 提到的,从文件中读取的数据不是 NULL 终止的,因此调用 strcpy 可以读取 str 的末尾。因此,您还需要解决这个问题:

int main (int argc , char **argv)
{
char str[517];
FILE *badfile ;
badfile = fopen ("badfile", "r");
if (!badfile) {
perror("fopen failed");
exit(1);
}
// read in 1 byte less than the buffer size, and capture the return value
int len = fread(str , sizeof(char), sizeof(str)-1, badfile);
if (len == -1) {
perror("fread failed");
fclose(badfile); // don't forget to close on error
exit(1);
} else {
// add the NULL terminator
str[len]='\0';
}
bof(str);
printf(" Returned properly \n");
fclose(badfile); // don't forget to close
return 1;
}

关于c - ubuntu32 位上的段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33806493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com