0

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?

8
  • 1
    What has your compiler to say to this line return *tmp; ? What type is tmp and what is *tmp? Commented Jan 31, 2022 at 10:33
  • 1
    @JHBonarius that dupe is about returning address of local nonstatic buffer. No relation to this question. Commented Jan 31, 2022 at 10:36
  • 1
    @ryden the compiler does not only think it is an integer. It is an integer. Actually a char to be more precise. Commented Jan 31, 2022 at 10:36
  • 1
    @JHBonarius that is again a dupe about local buffers. Please read this question before suggesting similar wrong dupes. Commented Jan 31, 2022 at 10:37
  • 2
    The root problem is this What compiler options are recommended for beginners learning C? Ensure that you get compiler errors when writing invalid C, so you don't waste time troubleshooting bugs that the compiler has already found for you. Commented Jan 31, 2022 at 11:05

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@ryden be aware that the warning "return makes pointer from integer without a cast" is almost always an error.
0

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**

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.