-3

The below code print

The string is : oldstring

I don't understand why?

#include<stdio.h>
char *func(){
    char str[1024];
    return str;
}
int main()
{
  char *g="string";
  strcpy(func(),g);
  g = func();
  strcpy(g,"oldstring");
  printf("The string is : %s",func());
  return 0;
}
  • 1
    Why? Because of undefined behaviour. – Daniel Fischer Mar 20 '13 at 16:06
  • `xxx` should not be declared as auto variable, no? – raina77ow Mar 20 '13 at 16:06
  • 1
    Because the variable `xxx` is on the stack and the stack contents aren't cleared and you just happened to be lucky. You have what is known as undefined behavior, so while it may work today, it may not tomorrow. – Nik Bougalis Mar 20 '13 at 16:07
  • UB 'cos auto/stack issue, plus I don't understand 'strcpy(gxxx(),g);' – Martin James Mar 20 '13 at 16:08
  • Yes, as Nik Bougalis says you are so lucky indeed. Just put one function call between the two and… well, you will see ;) – Jean Mar 20 '13 at 16:09
  • @MartinJames Well, in *theory* it copies whatever string `g` points to, to wherever the pointer returned from `gxxx()` points. Of course, that pointer points to junk (i.e. to the address of a temporary on the stack that has gone out of scope), so in *practice*... – Nik Bougalis Mar 20 '13 at 16:10
  • @NikBougalis: There's nothing lucky about a serious programming bug not exhibiting any obvious symptoms. – Keith Thompson Mar 20 '13 at 16:11
  • @KeithThompson No doubt. But I think that when read in context my use of the term "lucky" is quite different from what you imply. – Nik Bougalis Mar 20 '13 at 16:56

2 Answers2

0

As said: You are returning a local variable allocated on the stack. The variable ceases to exist the second you return. However the stack is not cleared, hence the behavior.

You need to allocate g on the heap. For that do:

void gxxx(char* xxx){

    //do sone stuff to xxx 
    return;
}

char *g = malloc(/*some size*/);
gxxx(g);
free(g);
Jean
  • 7,623
  • 6
  • 43
  • 58
0

The first: xxx is a local array of the gxxx() function. If you're trying to copy the string to this array after function exit, it causes undefined behavior.

The second: as I can see you are doing strcpy(g,"oldstring"); before printing the result. What did you expected?

Alex
  • 9,891
  • 11
  • 53
  • 87