The problem is that when you allocate memory in a function, it goes on the stack, and is removed and reused by the next function to be called.
So, you allocate an array of 100 characters on the stack, fill it, and return a pointer to it. Then you exit the function, which releases all the items on the stack, and goes back to your calling function. The pointer is perfectly valid (in the sense that it's in memory, and won't cause a access violation) but it is pointing to memory that is no longer assigned. When you call printf to show the string content, the same pointer goes over to the function, which is then free to use the stack for it's own variables. Since these share the same memory, it overwrites the content of your string data in the process of printing it!
Image it's a pile of coins: there are five coins in a pile, and you enter the telegram_input function. It needs space, so it adds 100 coins to the pile, and remembers where the first one is. it then writes a letter on each of the new 100 coins, and returns to the calling function. As part of the return, the pile of coins is returned to it's state before the function was called - 5 coins - and the printf function is called, which puts some coins of it's own on the pile. because the pointer you are passing about remembers the location of the coins in the pile - "they start at the sixth coin" - you end up not reading the right info, because your coins are long gone!
Hopefully this makes some sense - it's a lot easier with pictures and being able to see when your eyes glaze over...:laugh:
This is called a "hanging reference" and really has to be avoided. The best way to avoid it is to pass the buffer into the telegram-input function as a parameter, along with it's length if you are going to use it (and you should) so that the memory is always correct and available.
char* telegram_input(char* message)
{
printf("Write down the telegram: ");
gets(message);
return message;
}
int _tmain(int argc, _TCHAR* argv[])
}
printf("Write your message:\n\n");
char message[100];
telegram_input(message);
printf("The written message is: %s.", message);
return 0;
}
The other solution is to use the
malloc
function to allocate the memory within the telegram_input function - but then you must be sure to free the memory when you have finished with it.
malloc
allocates memory that is not on the stack (it is on a "heap" instead) so it does not have this problem.