-3

I want to know why doesn't the following work correctly? Though I have tried the other ways that work, but for the sake of more clarity I would like to know the problem occurring here.

char *fuc(char *s)
{
     char t[10];
     int r=0;
     while(s[r] != '\0')
     {
        t[r] = s[r];
        r++; 
     }
     t[r]='\0';
     return &t[0];   
}

main()
{
    char s[]="abcde";
    char *p;
    p=func(s);
    puts(p);
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
kashish
  • 15
  • 1

2 Answers2

3

In your fuc(), char t[10]; is a local variable. Once your function finishes execution, there is no existence of t. So, in the caller, the returned pointer becomes invalid.

Using that returned pointer further leads to undefined behaviour.

If you want to return the pointer from fuc(), you need to make use of dynamic memory allocation function , like malloc() and family. In that case, inside the caller function, once you're done using the memory, you need to take care for free()-ing the allocated memory, too.

That said, from the logical point of view, inside your fuc(), you're iterating over t without any check on the bounds. You should check for the size of t before using the index.

Furthermore, main() is not a proper form of the function. At Least, it should be int main(void).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

Array t is local to function func() so once you exit the function you can't access array t which will lead to undefined behavior.

You should allocate memory on heap.

char *t = malloc(10);

Now you can return a pointer from the function func()

Gopi
  • 19,784
  • 4
  • 24
  • 36