当我尝试运行测试时,为什么会出现“Segmentation Fault”错误?

我编写了一个函数来确定是否分配默认值(如果标志不存在,它会分配默认值,并且如果标志存在,则分配用户传递的值)。 我正在尝试用字符串测试我的函数,看看它是否给了我正确的数字。 当我尝试运行测试时,我不断收到“Segmentation Fault”,它编译,但测试不起作用。 🙁

这是我的头文件:

#ifndef COMMANDLINE_H #define COMMANDLINE_H #include "data.h" #include  struct point eye; /* The variable listed above is a global variable */ void eye_flag(int arg_list, char *array[]); #endif 

这是我的实现文件:

 #include  #include "commandline.h" #include "data.h" #include "string.h" /* Used global variables for struct point eye */ void eye_flag(int arg_list, char *array[]) { eye.x = 0.0; eye.y = 0.0; eye.z = -14.0; /* The values listed above for struct point eye are the default values. */ for (int i = 0; i <= arg_list; i++) { if (strcmp(array[i], "-eye") == 0) { sscanf(array[i+1], "%lf", &eye.x); sscanf(array[i+2], "%lf", &eye.y); sscanf(array[i+3], "%lf", &eye.z); } } } 

这是我的测试用例:

 #include "commandline.h" #include "checkit.h" #include  void eye_tests(void) { char *arg_eye[6] = {"a.out", "sphere.in.txt", "-eye", "2.4", "3.5", "6.7"}; eye_flag(6, arg_eye); checkit_double(eye.x, 2.4); checkit_double(eye.y, 3.5); checkit_double(eye.z, 6.7); char *arg_eye2[2] = {"a.out", "sphere.in.txt"}; eye_flag(2, arg_eye2); checkit_double(eye.x, 0.0); checkit_double(eye.y, 0.0); checkit_double(eye.z, -14.0); } int main() { eye_tests(); return 0; } 

错误在这里:

  for (int i = 0; i <= arg_list; i++) { ///^^ if (strcmp(array[i], "-eye") == 0) { sscanf(array[i+1], "%lf", &eye.x); //^^^ sscanf(array[i+2], "%lf", &eye.y); sscanf(array[i+3], "%lf", &eye.z); } } 
  1. i <= arg_list是错误的,因为你传入6,数组索引从0开始,最大值是5
  2. 当你从0迭代到5时i+1, i+2,i+3会给你超出范围的索引。

解决这个问题的绝对最简单的方法是在调试器中运行它。 您可能甚至不需要学习如何单步执行代码或任何操作 – 只需启动,运行和读取行。

如果您使用的是* nix系统:

  1. 使用-g标志编译代码。
  2. 加载为例如gdb a.out
  3. 现在运行它已加载 – (gdb) run
  4. 做任何你需要的东西来重现段错误。
  5. btwhere应该给你一个堆栈跟踪 – 以及导致你的问题的确切行。

我敢肯定你可以从那里解决这个问题作为答案; 但如果没有,了解确切的线条将使研究和解决变得更加容易。

您的循环条件错误。 它应该是i < arg_list
想想当i == arg_list时会发生什么。