C-为什么GCC编译和运行正常时,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时,它显示了core dovsted。

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

请帮助我理解错误。我搜索了很多,但不知道。谢谢您的高级。

我想您不会将参数传递给GDB,并且在第63行失败,试图将不存在的参数与选项进行比较。这是失败的来源。

尝试使用您的程序而无需ARG,并发现它也失败了。

如果所有ARG都是强制性的,则应在第62行之前放置if是正确的参数。

相关内容

  • 没有找到相关文章