gpt4 book ai didi

代码崩溃并出现错误段错误(核心转储)

转载 作者:行者123 更新时间:2023-11-30 18:28:10 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>

int NUM_ADS=7;
char *ADS[]=
{
"William: SBM GSOH likes sports,TV,dining",

"Matt:SWM NS likes art,movies,theater",``

"Luis:SLM ND likes books,theater,art",

"Mike:DWM DS likes trucks,sports and bieber"

"Peter:SAM likes chess,working out and art",

"Josh:SJM likes sports,movie theatre",

"Jed:DBM likes theater,books and dining"
};

int sports_no_bieber(char *s)
{
return strstr(s,"sports")&&!strstr(s,"bieber");
}

int sports_or_workout(char *s)
{
return strstr(s,"sports")||strstr(s,"working out");
}

int ns_theater(char *s)
{
return strstr(s,"NS")&&strstr(s,"theater");
}

int arts_theater_or_dining(char *s
{
return strstr(s,"arts")||strstr(s,"theater")||strstr(s,"dining");
}

创建了一个指向上面定义的函数的指针

void find(int(*match)(char*))
{
int i;

puts("Search Results:");
puts("------------------------------------");

for(i=0;i<NUM_ADS;i++)
{
if(match(ADS[i]))
{
printf("%s\n",ADS[i]);
}
}

puts("----------------------------------");
}

并将这些指针作为参数传递给这些函数,我收到错误段错误

int main()
{
find(sports_no_bieber);
find(sports_or_workout);
find(ns_theater);
find(arts_theater_or_dining);

return 0;
}

我正在创建函数指针并将它们传递给另一个函数

我通过 valgrind 运行它

Valgrind 输出

here is the output

可执行输出

output of code

我使用的是 ubuntu 17.04

最佳答案

ADS中,“Mike”字符串末尾没有有逗号。因此,编译器将[默默地]将其与“Peter”字符串连接起来以创建单个字符串。

这会将 ADS 数组缩短一个元素。结果是 ADS 将只有 6 个元素,而不是您期望的 7 个元素。

因此,find 中的 for 循环将越过数组末尾,导致段错误

关于代码崩溃并出现错误段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49496648/

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