Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange pointer problem

Tags:

c

pointers

The code segment given below compiles and when run gives 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;
}

whereas a slight modification to 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 this is happening ?

like image 889
Onkar Mahajan Avatar asked May 17 '26 04:05

Onkar Mahajan


2 Answers

char *temp = "string"; will create a pointer temp that points to a string litteral. This string literal is stored in the data segment of the executable code. It is immutable and the address is still valid after the function returns.

char temp[] = "string"; will allocate 7 characters on the stack and set them equal to 'string'. These are mutable characters. In your example, the returned value points to characters that are no longer valid when they function returns.

like image 62
JoshD Avatar answered May 19 '26 18:05

JoshD


In the first example, you are returning the address of a string literal. This literal exists as long as the program executes, so that code is safe.

In the second example, you create a (function local) array, which is initialised to contain the string string. You then proceed to return the address of (the first element of) this array, but the array gets destroyed as soon as you leave the function. This is what your compiler warns you about. Using the pointer returned from somefunc1 results in undefined behaviour, because it does no longer refer to an existing object.

like image 33
Bart van Ingen Schenau Avatar answered May 19 '26 16:05

Bart van Ingen Schenau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!