char *xyz()
{
char str[32];
strcpy(str,\"Hello there!\");
return(str);
}
void main()
{
printf(\"%s\",xyz());
}
When I call xyz(), is i
Yes, it is a dangling pointer. Your program invokes undefined behaviour.
On some systems it might crash your application, on others it might appear to work correctly. But either way, you should not do it.
Yes. Generally what you're trying to do is discouraged in general, but if you need to do that do this instead:
static char str[32];
Which will ensure that it stays around after the function exits.
It will indeed return a dangling pointer.
YES! it will return the pointer to "Hello there!" but since the xyz() released that memory you can't be sure that the string is still there so it's will be dangling pointer!
Yes it will generate a dangling pointer error.
When you call xyz(), 32 * sizeof(char) bytes will be allocated on the stack within xyz's stack frame. When you are working within xyz(), you are modifying and working on these bytes that have been allocated on the stack.
The return(str) call uses the str array name as a pointer, so you are actually returning the address to the str array. Once you have returned, the stack frame for xyz is unwound, and the local memory location that xyz had for str is no longer valid.
Back in your main function, the return value from xyz() (the address to the old str local variable in the xyz stack frame) is now passed to another function, printf. When printf generates it's own stack frame, it will actually be writing over the memory that was previously used to store str in xyz() ( since that is the next available memory on the stack).