Asking question

char *xyz()
{
   char str[32];
   strcpy(str,"Hello there!");
   return(str);
}


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

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

+5
source share
5 answers

Yes, it's a dangling pointer. Your program invokes undefined behavior.

On some systems, this may cause your application to crash, while for others, it may work correctly. But in any case, you should not do this.

+11
source

Yes, this will result in a dangling pointer error.

When you call xyz (), bytes of size 32 * sizeof (char) will be allocated on the stack in the xyz stack frame. When you work in xyz (), you modify and work on those bytes that were allocated on the stack.

return (str) str- , str. , , xyz , , xyz str .

xyz() ( xyz) printf. printf , , str xyz() ( ).

+5

.

+4

. , , , , :

static char str[32];

, .

+4

YES! it will return a pointer to "Hello!" but since xyz () released this memory, you cannot be sure that the string still exists, so it will be a dangling pointer!

+2
source

All Articles