【发布时间】:2020-03-06 13:48:57
【问题描述】:
有一些似乎可以工作的代码,但突然之间,每次运行代码时我都会遇到分段错误。
希望一双新的眼睛能帮助我找到问题。
它运行这条线 (printf("There are %d arguments excluding (%s)\n", count-1, *(input));) 并在之后崩溃。
我已经尝试使用 gdb 并检查了我的代码,但我似乎找不到问题。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getDiff(char **list[], int n);
int getSum(char *list[], int n);
int main( int count, char *input[] )
{
int total;
printf("There are %d arguments excluding (%s)\n", count-1, *(input));
if(strcmp(*(input+1),"sum") == 0){
int i;
for(i = 2; i<=count;){
printf("%d ", atoi(*(input + 2)));
i++;
if(i < count){
printf("+ ");
}
}
total = getSum(input, count);
}
if(strcmp(*(input+1),"diff") == 0){
total = getDiff(&input, count);
}
printf(" === %d ====", total);
}
int getDiff(char **list[], int n){
int i;
int total = atoi(**(list + 2));
for (i=3; i<= n;) {
int convert;
convert = atoi(**(list + i));
total = total - convert;
i++;
}
return total;
}
int getSum(char *list[], int n){
int i;
int total = atoi(*(list + 2));
for (i=3; i<= n;) {
int convert;
convert = atoi(*(list + i));
total = total + convert;
i++;
}
return total;
}
应该运行并返回从数字转换而来的整数的总和。
这是 gdb 告诉我的
程序收到信号SIGSEGV,分段错误。 0x00007ffff7b4c196 in __strcmp_sse42 () from /lib64/libc.so.6
【问题讨论】:
-
当它在 gdb 中崩溃时,堆栈跟踪是什么?你传递的命令行参数是什么?你不检查
count是什么,所以你很容易在input中越界索引。你可以考虑input[n]语法。我个人觉得它更容易阅读和理解。 -
@RetiredNinja 我的教授希望我使用指针,我在帖子中添加了 gdb 返回。
-
@chux-ReinstateMonica a.out sum 3 4
-
好奇的代码使用
int getDiff(char **list[], int n){而不是int getDiff(char *list[], int n){。嗯。为什么需要额外的间接级别? -
gdb 输出中的
bt命令是什么?它应该向您显示代码中导致崩溃的行。
标签: c pointers segmentation-fault coredump