开发者

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

开发者 https://www.devze.com 2023-02-13 03:09 出处:网络
Assume we have the following: int main(void) { char* ptr; printf(\"%c\\n\",ptr[24]);// junk value ptr[24] = \'H\';

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

   retur开发者_JAVA百科n 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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消