Quote:
Originally Posted by George2
When executing the following statement,
--------------------
bool* a = new bool[8];
--------------------
There is a segmentation fault error
|
If you got
this error, George, then I am sure that the root cause of the problem lies
elsewhere.
This is what we call a "stack scribble," where the internal data structures used by
malloc et al have been .. hosed.
Unfortunately, the real source of the problem could have happened anywhere, quite some time ago.
The most common cause, however, is a
double-free. You attempt to
free() the same region of memory more than once. A "stale pointer." (Less often, an uninitialized pointer-variable leads you to free an area that you had never
malloc()ed. "Stack scibbles" can also occur by overwriting the end of a block.)
{P.S. There are many different flavors of allocating and freeing memory... they're all the same for this discussion.}
Here's the best thing to do: after
every single free() (or its equivalent), insert a statement to expressly set the affected pointer-variable to NULL:
Code:
free(fooptr);
fooptr = NULL; // <- add this
Furthermore, anytime you create a pointer-variable, explicitly set it to NULL
on creation unless you
know that it will always get a known value.
Code:
struct foobar *fooptr = NULL; // add "= NULL"
What this little bit of self-discipline does for you is to enforce the following rule:
"At all points throughout this program, any pointer-variable either points to what is known to be a valid structure in memory, or it is known to contain NULL."
free() checks for NULL and does nothing if you attempt to free NULL, but it
does not otherwise check that the pointer value makes sense, nor that it points to an area of memory that has not already been freed.
Incidentally... there are implementations and variants of these routines which add "boundary tags" on either side of the allocated memory-blocks. They're a painless and efficient way to detect this nasty problem. They work by slightly increasing the size of each allocation-request to make room for a short "tag" at the beginning and at the end of each block. They hand you a pointer to the space in the middle... which they initialize to known-zeroes. When freeing or resizing the block, they first make sure that the tags still exist (they weren't overwritten), and that they don't indicate an already-freed block.
Very powerful, and something that you can actually leave in production-release code without consequence.