Fixing a Segmentation fault: 11

本小妞迷上赌 提交于 2019-12-25 18:14:09

问题


I'm currently trying to convert an integer string (like "509" as type char) to an int in C. However once I added the portion of code that checked to see if the value should be negative I get a segmentation error. I tried doing some research and found that its because of using pointers wrong or accessing memory I don't have permission to. But I can't seem to figure out where I'm going wrong. This is my first C class so I am new to it, any help would be much appreciated. Thanks!

#include <stdio.h>
#include <string.h>

int toInteger(char *string){
    int length = strlen(string); 
    int value = 0; 
    if(strcmp(string[0], "-") == 0){
        for(int i = 1; i < length; i ++){
            if((string[i] - '0') < 0 || (string[i] - '0') > 9){
                printf("string must be entirely numeric values.\n"); 
            }
            else{
                value = value * 10 + (string[i] - '0');
            }
        }
        value = value * -1; 
    }
    else{

        for(int i = 0; i < length; i ++){
            if((string[i] - '0') < 0 || (string[i] - '0') > 9){
                printf("string must be entirely numeric values.!\n"); 
            }else{
            value = value * 10 + (string[i] - '0');
            }
        }
    }
    return value;   
}

int main(int argc, char *argv[]){

int x = argc; 
char *variable = argv[1]; 
char *function = argv[2];

if(strcmp(function,"1") == 0){
        int asInteger = toInteger(variable);
        printf("%d\n",asInteger);
    }
else {
    printf("incorrect function number"); 
}
return 0; 
}

The code worked when the function was only this

int toInteger(char *string){
int length = strlen(string); 
int value = 0; 

    for(int i = 0; i < length; i ++){
        if((string[i] - '0') < 0 || (string[i] - '0') > 9){
            printf("string must be entirely numeric values.!\n"); 
        }else{
        value = value * 10 + (string[i] - '0');
        }
    }
    return value;   
}

but once I added the other loop to check for a negative sign it started giving me the segmentation fault: 11


回答1:


Matt McNabb already hinted

if(strcmp(string[0], "-") == 0){

is wrong. strcmp wants two strings, you gave it a char and a string. Do

if(string[0] == '-')){

And yes, never ignore warnings, the compiler is trying to help you. Although it is arguable that its not helping, if it had fatalled instead you would have tried to fix it



来源:https://stackoverflow.com/questions/28422106/fixing-a-segmentation-fault-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!