Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you initialize a junk value to something in C?

Tags:

c

pointers

memory

Assume we have the following:

int main(void) {
   char* ptr;

   printf("%c\n",ptr[24]);  // junk value

   ptr[24] = 'H';

   printf("%c\n", ptr[24]);  // prints H

   return 0;
}

When I change the junk value to something else, does that mean I am corrupting memory or is this value literally junk so it doesn't matter what new value I assign to it?

like image 568
user246392 Avatar asked Feb 22 '11 08:02

user246392


3 Answers

Your program exhibits undefined behaviour which means: Literally anything may happen and it's still be coverd by the standard as being undefiend. And when I say anything, I mean it in the full extent. It would be even valid for your computer becoming sentient and chase you down the street.

Well, what's usually happens, but that's not warranted, is that you're writing into unmapped address space (on a modern OS with paged memory) causing a segmentation fault or a bus error (depending on architecture, OS and runtime implementation).

ptr is an unitialized pointer, which means the pointer's value is yet to be defined. A undefined pointer, by definition, points to nothing and everything, i.e. no valid object at all. The only way to make that pointer valid is assigning it the address of a proper C object of the type the pointer dereferences to.

BTW: Plain C has very, very strict typing rules. I sometimes say it's even stricter than C++, because its lack of the implicit conversion operator and function overloading. But its sloppy type casting and bad compilers ruined its reputation with respect to type safety.

like image 153
datenwolf Avatar answered Oct 20 '22 02:10

datenwolf


You are accessing invalid memory locations which invokes undefined behavior. Anything might happen, it can't be predicted.

like image 33
Naveen Avatar answered Oct 20 '22 02:10

Naveen


Since most C implementations allow you to access invalid memory locations, you are actually assigning the 'H' value to that position.

But you cannot trust what's gonna happen next. Maybe your program fails, maybe you damage memory in use by other program, or, in a multithreaded environment, another program may overwrite that value.

like image 40
elitalon Avatar answered Oct 20 '22 02:10

elitalon