• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Zodiak

Array Out Of Bounds Allowed?

10 posts in this topic

Hey everyone,

How come I can access non-existent array values and not get any errors??? It just prints 0 when the index is out of bounds, as if the value of that index is 0. Please explain.

[code]#include <iostream>

using namespace std;

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int main()
{
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl << endl; // this works as expected
}

cout << arr[10] << endl // this prints 0
<< arr[11] << endl // this prints 0
<< arr[22]; // this prints 0 as well. No errors, nothing.

return 0;
}[/code]

Using Code::Blocks.
0

Share this post


Link to post
Share on other sites
Welcome to the wonders of C and C++. Arrays little more than pointers in memory, with the index you specify being N*sizeof(arrayType) from that pointer. If you specify more than the array, you can read/write to some bit of memory outside of the array. This used to be the source of like 95% of computer exploits (though cross site scripting, SQL injection, and the fact that few people use C or C++ anymore have reduced that figure significantly).

That you happened to get 0 while going out of bounds is chance.
0

Share this post


Link to post
Share on other sites
A valid C++ implementation is not obliged to perform bounds checking on array access. Many will put limited bounds checking in debug mode. For example, were the array dynamically allocated, and you wrote past the end, when you deallocate the array the heap code can sometimes detect this and report an error.

Technically speaking your program is ill-defined as it uses what the C++ standard calls "undefined behaviour". There is no requirement for the compiler or runtime to try and detect or handle such usage. Indeed, undefined behaviour is often used when such detection would be expensive to perform. This allows C++ compilers to generate efficient code, they don't need to account for the programmer misbehaving. This design mentality is summed up as [b]the programmer is always right[/b].

This is one of the reasons why containers like std::vector are preferred, in debug mode they can do full bounds checking.
0

Share this post


Link to post
Share on other sites
Thank you for your replies! I was aware that it's bad practice and shouldn't be done. But I thought this kind of code results in an [b]error[/b], program crash, memory leak etc.
My question was: why is the result simply 0? Nothing wrong, just 0? How come these random memory addresses are 0? Why not 0xfff00 or something?
0

Share this post


Link to post
Share on other sites
Ok, this is what Visual C++ 2010 does:
"'console.exe': Loaded 'C:\Documents and Settings\Gleb\My Documents\Visual Studio 2010\Projects\console\Release\console.exe', Symbols loaded.
'console.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll', Cannot find or open the PDB file
'console.exe': Loaded 'C:\WINDOWS\system32\kernel32.dll', Cannot find or open the PDB file
'console.exe': Loaded 'C:\Program Files\AVAST Software\Avast\snxhk.dll', Cannot find or open the PDB file
'console.exe': Loaded 'C:\WINDOWS\system32\msvcp100.dll', Symbols loaded.
'console.exe': Loaded 'C:\WINDOWS\system32\msvcr100.dll', Symbols loaded.
The thread 'Win32 Thread' (0x8a8) has exited with code -1073741510 (0xc000013a).
The program '[3036] console.exe: Native' has exited with code -1073741510 (0xc000013a)."

and the out of bounds values are: 1, 374455, 0

Code::Blocks still just prints three zeroes.

That's my question. I know VC++ and CB are different, but what's the underlying reason for such behavior? I'm accessing random memory, why does CB return zeroes and VC returns something else? Exact same source.
0

Share this post


Link to post
Share on other sites
[quote name='Zodiak' timestamp='1319723919' post='4877549']
Thank you for your replies! I was aware that it's bad practice and shouldn't be done. But I thought this kind of code results in an [b]error[/b], program crash, memory leak etc.
My question was: why is the result simply 0? Nothing wrong, just 0? How come these random memory addresses are 0? Why not 0xfff00 or something?
[/quote]

The results of undefined behavior are... undefined. There is no definition for what should happen, so what's the point of asking why an undefined result is a certain way?It doesn't really matter.

The real explanation lies in the implementation details, which is something you should probably avoid.
0

Share this post


Link to post
Share on other sites
[quote name='Zodiak' timestamp='1319723919' post='4877549']
My question was: why is the result simply 0? Nothing wrong, just 0? How come these random memory addresses are 0? Why not 0xfff00 or something?
[/quote]

It's not a random memory address, it's the int value of the bits at that memory address. Sometimes it will not be 0. Sometimes that memory address will be invalid and you'll crash. Sometimes that memory address will be different variables in your program. Sometimes that memory address will be the actual instructions that your program [i]is[/i].

It is an error as far as you made a mistake, but C and C++ make no guarantees about what happens when you do it. They do that a lot.
0

Share this post


Link to post
Share on other sites
[quote name='Zodiak' timestamp='1319724333' post='4877551']
That's my question. I know VC++ and CB are different, but what's the underlying reason for such behavior? I'm accessing random memory, why does CB return zeroes and VC returns something else? Exact same source.
[/quote]

Undefined behavior, as has been said. It may only return zeros only on Thursdays, or if your last name is "Smith", or if you are wearing a red shirt. Although this is obviously just a humorous answer, it's just about as useful an answer* you may get. The fun** part is that such undefined behavior can also cause crashes, in seemingly unrelated and completely different parts (of seemingly valid!) code -

but only on Thursdays, or if your last is "Smith", or if you are wearing a red shirt. :)

* Some compilers (and probably only on debug builds) will fill in certain memory areas with specific values in order to more easily track down memory bugs.

** Not really fun, these types of bugs are notoriously frustrating to squash.
0

Share this post


Link to post
Share on other sites
[quote name='FlyingDutchman' timestamp='1319725333' post='4877559']
Xcode would tell u that the array is out of bound as a compiler warning!
[/quote]

So would g++ if you compiled with -Wall (all warnings enabled), as you should. I would be surprised if Visual C++ doesn't warn about something as blatant as this.

Someone said that "undefined behavior" means "it works when you first try it, it passes all your tests and it explodes in your face when you are showing the program to your boss or your most important customer." :)
0

Share this post


Link to post
Share on other sites
Strange, I get [url="http://catb.org/jargon/html/N/nasal-demons.html"]nasal demons[/url] ;-)
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0