ryden
ryden

Reputation: 189

segmentation fault when returning string from function

I was wondering what this code should print. I wanted to check whether it prints we can, can we or we can, but instead i got segmentation fault.

Here is the code:

char* mysubstr() {
    char* x = "Yes we can, can we";
    char* y = "we can";
    char* tmp = x;
    
    while(*tmp) {
        if (*tmp == *y)
            return *tmp;
        tmp++;
    }
    return x;
}


void main() {
    printf("%s", mysubstr());
}

I think the wrong part is the return *tmp;, but why? What's wrong with that?

Upvotes: 0

Views: 618

Answers (2)

user17974802
user17974802

Reputation:

Following works:

char* mysubstr()
   {
       char* x = "Yes we can, can we";
       char* y = "we can";
       char* tmp = x;
  
       while(*tmp)
       {
           if(*tmp == *y)
           {
               return (char*) tmp;
           }
           tmp++;
       }
       return (char*) x;
   }
  
   int main()
   {
       printf("%s", mysubstr());
       return 0;
  }

And the answer is:

**We can, can we**

Upvotes: 0

Gerhardh
Gerhardh

Reputation: 12404

Your compiler basically already told you what is wrong:

return makes pointer from integer without a cast

This is because you define a function returning a char * but you return a char.

With char *tmp = x; you define a pointer and in your return statement you dereference it. Hence you return (char*)'w'

If you use that return value for printf value 'w' is taken an address which causes your crash.

You should just do return tmp;

This is not the only issue in your code. Your function name indicates you want to make some substring function. Bur your code returns immediately it found a match of first letter in second string. You don't verify if the other character also are same.

Upvotes: 1

Related Questions