Weird pointer issue

The code segment below compiles and, at startup, produces the result as:

$ make
gcc -g -Wall -o test test.c
$ ./test
string

/ * code1 * /

#include<stdio.h>
char *somefunc1()
{
   char *temp="string";
   return temp;
}
int main(int argc,char *argv[])
{
   puts(somefunc1());
   return 0;
}

while a small modification of this code gives different results:

$ make
gcc -g -Wall -o test test.c
test.c: In function ‘somefunc1’:
test.c:5: warning: function returns address of local variable
$ ./test

/* code 2 */

#include<stdio.h>
char *somefunc1()
{
   char temp[] ="string";
   return temp;
}
int main(int argc,char *argv[])
{
   puts(somefunc1());
   return 0;
}

Why is this happening?

+3
source share
4 answers

char *temp = "string";creates a pointer tempthat points to a string litteral. This string literal is stored in the data segment of the executable code. It is unchanged, and the address remains valid after the function returns.

char temp[] = "string";allocates 7 characters on the stack and sets them equal to 'string'. These are volatile characters. In your example, the return value indicates characters that are no longer valid when the function returns.

+4
source

. , , .

( ) , , string. ( ) , , . . , somefunc1, undefined, .

+4

, , " " .

+1

char * temp = "string"; temp . char temp [] = "string";   , , . , something1, . , , . .

-1

Source: https://habr.com/ru/post/1769310/


All Articles