Preventing stack overflows in C ++ using arrays?
Just resize the array when you get close to the "overflow condition", i.e. when the next item no longer fits. Or use std::vector
which you can easily change.
Not sure, but do you know a class std::stack
that implements a stack that automatically resizes in C ++?
[EDIT] If you don't want to resize but don't work as expected, throwing an exception is the best you can do. For example, you can define StackOverflowException
and throw it away if there is no free space, so customers can respond.
source to share
You can use std :: stack to implement the stack. If you're looking for a homemade answer, keep an array of data items (or pointers to them). This array can grow or shrink as the stack grows or shrinks. The growth / contraction factor * determines how much you care about speed or size optimization.
* By growth / shrinkage ratio, I mean how many elements you add or remove as you grow or shrink. These are, of course, two-value values ββor multiples, which you can simply add or multiply by a prime number (for example, + = 4096, * = 2). Using large values ββhelps prevent the stack from resizing, resulting in faster code, but consumes more memory. Smaller values ββhave the opposite effect and can even cause memory fragmentation on non-MMU systems (for example, some portable devices). For an implementation using buckets, this is basically your bucket size.
For the stack, you can use a linked list, a linked list with buckets, an alloc'd array (using malloc / realloc / free), std :: vector, or other linear structures.
If you need code size, use std :: stack (duh) or std :: vector as a starting point. However, since most C ++ compilers compile them as bulky sets of functions, you would probably roll out the light class using the malloc'd array.
source to share
While this answer provides no implementation hints, it answers how often you can protect yourself from certain bugs, such as a buffer overflow. GCC has a flag for this:
-fmudflap -fmudflapth -fmudflapir
For interfaces that support it (C and C ++), handle all the risky pointer / array dereferencing operations, some standard library / library heap functions, and some other related range / validity test constructs. Modules equipped with such tools must be protected from buffer overflows, invalid heap use, and some other classes of C / C ++ programming errors. The tool relies on a separate runtime library (libmudflap) that will be linked to the program if -fmudflap is referenced for the time. The execution time of the tool is controlled by the MUDFLAP_OPTIONS environment variable. See "Env MUDFLAP_OPTIONS = -help a.out" for its options.
Typically, this requires compiler support because it cannot overload the subscript operator []
for its own type array char[]
or type pointer char*
.
source to share