gpt4 book ai didi

c - 为什么在 GCC 编译运行正常时 GDB 显示段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:55 25 4
gpt4 key购买 nike

我正在写一个小代码来分配空间并在其中读写以测试缓存监控工具。代码如下:

#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]);

请帮助我了解错误。我搜索了很多但无法弄清楚。先谢谢你。

最佳答案

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

尝试在没有 args 的情况下使用你的程序,看看它是否也失败了。

如果所有参数都是强制性的,您应该在第 62 行之前放置一个 if 来检查提供的参数数量是否正确。

关于c - 为什么在 GCC 编译运行正常时 GDB 显示段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55298482/

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