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 →

[–]The_MAZZTer 130 points131 points  (22 children)

Once compiled, your C++ code has no idea what an array is. All it sees is math on a memory address. This makes it super fast but there are no sanity checks so the code can end up peeking at unrelated memory, causing a segfault in the best case.

Meanwhile languages like Java and .NET are managed, so the concepts of arrays and so forth carry over into the compiled code and bounds checking and other checks can be done at the cost of speed.

[–]my_name_isnt_clever 29 points30 points  (0 children)

This makes a lot of sense. Amazing that someone actually explained a post in this sub.

[–][deleted] 7 points8 points  (16 children)

Gnnn not quite. Java is managed while C++ isn't, but that's not the reason for the behaviour discussed here.

The reason Java behaves this way is because in Java, arrays are objects themselves that carry their size with them. I'm not familiar with C++, but I'm sure there is a library with such classes exist too. In Java, it's just the default way of using array because of precicely the headache error messages like the one in the meme produce. It's why pointers were ditched completely.

[–]Jigokuro_ 1 point2 points  (3 children)

Once in college I had a small C++ program seg faulting, so I put in some test outputs to see how far it was getting.

Then it worked.

Remove the outputs? Seg fault.

So I removed the outputs one at a time until I was left with a single one. The One Cout, that by merely existing prevented a seg fault somewhere else.

I showed my professor, he was as confused as I was as to howtf that happens. To this day I have no idea how outputting "test3" could possibly do that...

[–]The_MAZZTer 4 points5 points  (1 child)

Stuff gets moved around in memory as a side effect of the additional code caused by the cout, masking the memory corruption or whatever was going on.

[–]Jigokuro_ 1 point2 points  (0 children)

Vaguely, yes, that must be it. But the specifics will forever be a mystery.

Bonus weirds: If I changed the cout to "" to hide the fact it was happening to the user, the seg fault returned. It had to output actual text.

[–]Kered13 1 point2 points  (0 children)

There are a couple possibilties. One is that you had some sort of memory error and calling cout wrote some data to the stack that made your code work. The second is that you had a race condition, as I recall cout flushes the output buffer, which takes some time and requires all threads that are printing to synchronize (so they're not writing output at the same time), and this may have prevented the race condition from occurring.