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

标签 c

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

我正在尝试使用函数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/

相关文章:

c - 通过 GTK 或 GDK 直接在屏幕上绘图

c - 如何在编译时在依赖文件中添加用户定义的依赖项

计算 C 中的色散

c - 为什么在 rand 中使用 1103515245?

c - 结构 : invalid type argument of '->' 出现问题

c - Linux和C,程序错误

c - 快速CRC算法?

c - 如何在纯 C 中启动线程?

c - 带有递归和回溯的骑士​​之旅代码

c - 做一会儿还是一会儿?