star_sh00ter
star_sh00ter

Reputation: 1

Where is my segmentation fault occuring?

I am very new to C, so I apologize if this is a silly question. I am getting a segmentation fault, and when I run gdb, I am not getting a line number to demonstrate what is causing the fault like I usually do. Instead, I get something along the lines of:

0x00000000004012ff in find_any_ptr ()

I am writing a method to return a pointer to the first occurrence of any character in stop in the given string, or NULL if string doesn't contain any of the characters.

char *find_any_ptr(char *string, char* stop){
    char* ch1 = string;
    char* ch2 = stop;
    int retComp = strlen(string);
    char* retChar;
    while(*ch2 != '\0'){
        int temp = 0;
        while(*ch1 != '\0'){
            if(*ch2 == *ch1){
                if(temp < retComp){
                    *retChar = ch1;
                    retComp = temp;
                }
            }
            temp++;
            ch1++;
        }
        ch2++;
    }
    if(retComp == strlen(string)){
        return NULL;    //NULL has been defined elsewhere
    }else{
        return retChar;
    }
}

If anyone sees where the underlying issue is, I would really appreciate your help. :) Thank you!

Upvotes: 0

Views: 114

Answers (2)

BusyProgrammer
BusyProgrammer

Reputation: 2781

The following statement:

*retChar = ch1;

Causes the segmentation fault because you are trying to dereference an uninitialized pointer; to avoid this, you should change that statement to:

retChar = ch1;

This statement stores the address of ch1 in retChar, not the char value that is stored in ch1; this is probably what you are looking to do.

Upvotes: 0

imhotap
imhotap

Reputation: 2500

Change *retChar = ch1; to retChar = ch1; ie. you're dereferencing the retChar pointer when it isn't initialized to something and you probably just want it to assign the value of the ch1 pointer (the address not the char it points to).

Upvotes: 1

Related Questions