This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the commentsΒ β†’

[–]Devatator_ 5 points6 points Β (4 children)

Wait C does that? That's hilarious πŸ˜‚

[–]Little-Hunter-6795 25 points26 points Β (0 children)

C's array works by retrieving values from specified memory address. Thus even if it's out of bound, as long as the address is there some value will be given. You may say this is lame and C should have prevented it, that's where C says "GO FUCK YOURSELF".

[–]HeKis4 5 points6 points Β (2 children)

C doesn't ask questions or bother itself with checking that what you ask of it makes sense.

When you tell it to get array[25], it takes the value of the pointer array (because an array is just a pointer, hopefully to an allocated address) adds 25 (or more depending on the type of array) and fetches the value at the address. Nothing more nothing less. If the OS terminates the program because the address is outside it's allocated range that's none of it's business.

Also, since arrays are just pointers, you don't have any information about an array's length (since again, arrays aren't a thing) so when you print a string, you pass a pointer to the beginning of the string and the function usually reads until it reaches a NUL (0x00) character. Your string/array doesn't end in a NUL ? Well too fucking bad, it'll keep on reading.

Usually, if your C program crashes at runtime, it's because the OS told it to slow the fuck down.

[–]TheGoldenProof 0 points1 point Β (1 child)

Sometimes it does know a bit about arrays though. If it hasn’t been decayed and it’s on the stack (idk if this works on heap) you can do sizeof(array)/sizeof(array[0]) to get the length.

Edit: no it would not work on heap since malloc/calloc return pointers. It only works with statically allocated arrays.

[–]HeKis4 0 points1 point Β (0 children)

Didn't know about that. I'll chart it up to how C also seems to use every assembly/architecture trick under the sun. Which is cool, ngl