C dangling pointer question

后端 未结 5 496
北海茫月
北海茫月 2020-12-16 06:46
char *xyz()
{
   char str[32];
   strcpy(str,\"Hello there!\");
   return(str);
}


void main()
{
  printf(\"%s\",xyz());
}

When I call xyz(), is i

相关标签:
5条回答
  • 2020-12-16 06:50

    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.

    0 讨论(0)
  • 2020-12-16 06:50

    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.

    0 讨论(0)
  • 2020-12-16 06:56

    It will indeed return a dangling pointer.

    0 讨论(0)
  • 2020-12-16 06:56

    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!

    0 讨论(0)
  • 2020-12-16 07:07

    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).

    0 讨论(0)
提交回复
热议问题