当GCC正常运行时,GDB为什么会显示分段错误

时间:2019-03-22 11:18:09

标签: c segmentation-fault gdb

我正在向分配空间编写一小段代码,并对其进行读写操作,以测试高速缓存监视工具。代码如下:

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

#define times 2

void write_in_space(int* x, int size){
  printf("\n Entering write in space \n");
  int i;
  for(i = 0; i< size; i++){
    *(x + i) = i;
    i++;
  }
  printf("\n Exiting write_in_space \n");
}

void read_in_space(int* x, int size){

  printf("\n Entering read_in_space \n");
  int i = 0;
  while(i < size){
    *(x + i);
    i++;
  }
  printf("\n Exiting read_in_space \n");
}

void assign_and_work(int k, int l, int m, int mm){

  printf("\n Entering assign_and_work \n");
  int* space;
  space = (int*)malloc(k * sizeof(int));

  if(mm == 3){
  write_in_space(space , k);
  sleep(m);
  read_in_space(space, l);
}

  else if(mm == 1)
    read_in_space(space, l);

  else if(mm == 2)
    write_in_space(space,k);


  printf("\n Exiting assign_and_work \n");
  free(space);

}

//Driver Code

int main(int argc, char **argv){
  int read_space = 0;
  int write_space = 0;
  int sleep_time = 0;
  int i = 1;
  int mode = -1;
  int time = times;
  do{
    if(strcmp(argv[i],"-w") == 0)
      write_space = atoi(argv[i + 1]);
    if(strcmp(argv[i],"-r") == 0)
      read_space = atoi(argv[i + 1]);
    if(strcmp(argv[i],"-s") == 0)
      sleep_time = atoi(argv[i + 1]);
    //if(strcmp(argv[i],"-time") == 0)
      //times = atoi(argv[i + 1]);
    i = i + 1;
  }while( i < argc);

  if(write_space == 0 && read_space > 0)
    mode = 1;
  else if(read_space == 0 && write_space > 0)
    mode = 2;
  else
    mode = 3;

  if((read_space > write_space) && (mode == 3) ){
    write_space = read_space;
  }
    while(time > 0){
    assign_and_work(write_space, read_space, sleep_time, mode);
    time--;
  }


return 0;

}

问题是当我使用命令

进行编译时
gcc -o rw readwrite.c

并运行./rw -r 500000 -w 800000 -s 20可以正常工作。但是当我尝试使用gdb时,它会显示以下消息

Program received signal SIGSEGV, Segmentation fault.

__strcmp_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcmp-sse2-unaligned.S:31
31  ../sysdeps/x86_64/multiarch/strcmp-sse2-unaligned.S: No such file or directory.
(gdb) 

我无法理解该错误。我尝试使用gdb是因为当我通过argv花费时间作为用户输入时,它显示了核心转储。

 if(strcmp(argv[i],"-time") == 0)
      times = atoi(argv[i + 1]);

请帮助我理解故障。我搜寻了很多,但找不到。 谢谢你。

1 个答案:

答案 0 :(得分:5)

我猜您没有将参数传递给GDB,并且在第63行尝试将不存在的参数与选项进行比较时失败。这是失败的根源。

尝试在不使用args的情况下使用程序,并查看它也会失败。

如果所有参数都是强制性的,则应在第62行之前放置if,以检查提供的参数数是否正确。