开发者

C dangling pointer question

char *xyz()
{
   char str[32];
   strcpy(str,"Hello开发者_JS百科 there!");
   return(str);
}


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

When I call xyz(), is it will return a dangling pointer ? Thanks


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


It will indeed return a dangling pointer.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜