0

I have implemented my own strchr() function in C. When calling the function and saving the output into a pointer I go ahead and print the stream of chars and the result looks fine. However, after calling a printf(), my stream of chars gets cut off for some reason. Does anyone understand why? Here is my code:

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

char *mon_strchr(const char *chaine, int car)
{
        int j = 0, i;
        char *pbuff, buff[256];
        pbuff = buff;

        for (i = 0; chaine[i] != '\0'; i++)
        {
                if ((int)chaine[i] == car)
                        break;
                i++;
        }
        for (i; chaine[i] != '\0'; i++)
        {
                buff[j] = chaine[i];
                j++;
        }

        return pbuff;
}

int main()
{
        const char str[] = "http://www.tutorialspoint.com";
        const char ch = '.';
        char *ret;

        ret = mon_strchr(str, ch);

        printf("%s\n", ret);
        printf("String after |%c| is\n", ch);
        printf("%s\n", ret);
        return (0);
}

And this is the output:

.tutorialspoint.com
String after |.| is
.tutoria
Mister Tusk
  • 145
  • 1
  • 6
  • 1
    `return pbuff` is returning a pointer to a local array, which is destroyed when the function ends. – Barmar Feb 11 '20 at 22:34
  • So you're causing undefined behavior when you try to print it. – Barmar Feb 11 '20 at 22:35
  • You're returning a pointer to a local variable, `buff`, which is no longer valid once you return from the function. The space it occupied is reused — so the string gets trampled on. You also forgot to null-terminate the string you copy into `buff`. – Jonathan Leffler Feb 11 '20 at 22:35
  • 2
    Why do you think you need to copy into another buffer? `strchr()` is supposed to return a pointer into the string you gave it, not some other string. – Barmar Feb 11 '20 at 22:36
  • @Barmar Thanks, I did not know that – Mister Tusk Feb 11 '20 at 22:40

0 Answers0