Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a char* that went out of scope

Tags:

c

I recently started programming in C again after having programmed in C++ for a while, and my understanding of pointers is a bit rusty.

I would like to ask why this code is not causing any errors:

char* a = NULL; {     char* b = "stackoverflow";     a = b; }  puts(a); 

I thought that because b went out of scope, a should reference a non-existing memory location, and thus their would be a runtime error when calling printf.

I ran this code in MSVC about 20 times, and no errors were shown.

like image 249
MattMatt2000 Avatar asked Jun 13 '17 19:06

MattMatt2000


1 Answers

Inside the scope where b is defined, it is assigned the address of a string literal. These literals typically live in a read-only section of memory as opposed to the stack.

When you do a=b you assign the value of b to a, i.e. a now contains the address of a string literal. This address is still valid after b goes out of scope.

If you had taken the address of b and then attempted to dereference that address, then you would invoke undefined behavior.

So your code is valid and does not invoke undefined behavior, but the following does:

int *a = NULL; {     int b = 6;     a = &b; }  printf("b=%d\n", *a); 

Another, more subtle example:

char *a = NULL; {     char b[] = "stackoverflow";     a = b; }  printf(a); 

The difference between this example and yours is that b, which is an array, decays to a pointer to the first element when assigned to a. So in this case a contains the address of a local variable which then goes out of scope.

EDIT:

As a side note, it's bad practice to pass a variable as the first argument of printf, as that can lead to a format string vulnerability. Better to use a string constant as follows:

printf("%s", a); 

Or more simply:

puts(a); 
like image 106
dbush Avatar answered Sep 19 '22 19:09

dbush