gpt4 book ai didi

c - 程序无法运行可能是因为段错误

转载 作者:行者123 更新时间:2023-11-30 16:25:15 25 4
gpt4 key购买 nike

请告诉我为什么我的程序无法运行。我认为这可能是一个段错误,但我无法识别它。如果可以的话请指正。

我正在尝试使用函数chartoint()将char数组转换为int数组,当我将其从main中删除时,它可以工作,所以问题出在函数中。

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

void chartoint(char c[],int * x){
int i;
while(c[i]!='.'||c[i]!='\0'){
if((int)c[i]>57){ *(x+i) = (int)c[i] - 54;}
else{ *(x+i) = (c[i]-'0'); }
i++;
}
*(x+i) = -1; i++;
while(c[i]!='\0'){
if((int)c[i]>57){ *(x+i) = (int)c[i] - 54;}
else{ *(x+i) = (c[i]-'0'); }
i++;
}
}

int main(){
int n;
printf(" number of characters ");
scanf("%d",&n);
char c[n+1];
for(int i=0; i<n; i++){
scanf("%c",&c[i]);
}
c[n]='\0';
int * x = (int*)malloc(n*sizeof(int));
chartoint(c,x);
for(int i=0; i<n; i++){
printf("%d",*(x+i));
}
free(x);
return 0;
}

最佳答案

您需要学习如何使用调试器。

这是使用调试器运行 C 程序(在本例中为 gdb)时的输出。我将你编译的程序命名为t:

$ gdb ./t
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.3) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./t...done.
(gdb) r
Starting program: /home/youruser/t
number of characters 3
a

Program received signal SIGSEGV, Segmentation fault.
0x00000000004006ba in chartoint (c=0x7fffffffe540 "\na\n", x=0x602010) at t.c:6
6 while(c[i]!='.'||c[i]!='\0'){
(gdb) bt
#0 0x00000000004006ba in chartoint (c=0x7fffffffe540 "\na\n", x=0x602010) at t.c:6
#1 0x0000000000400884 in main () at t.c:29
(gdb)

这基本上是说,在运行第 6 行时,您遇到了段错误 (SIGSEGV)。原因可能是 i 它在没有先初始化的情况下就被使用了。

如果您使用 IDE 来执行此操作(Visual Studio、Visual Studio Code),您可能会拥有嵌入式调试器。

关于c - 程序无法运行可能是因为段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459213/

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