Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading