程序无法正常工作,可能是导致分段错误

时间:2018-11-24 14:33:33

标签: 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;
}

1 个答案:

答案 0 :(得分: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),则可能会具有嵌入式调试器。