[mercury-users] Beware big static buffers in C++ objects

Ondrej Bojar oboj7042 at ss1000.ms.mff.cuni.cz
Sat Mar 29 02:43:56 AEDT 2003


For those who helped me with catching the 'strange segfault' for over
fourteen days, here is the solution.

The code of my colleague is a poor C++ implementation. He defines a class
with a static buffer of a big size.

#define BUFFER_SIZE 10000
              // or 100000
class CReport {
  char Buffer[BUFFER_SIZE]

Then he statically allocates an object of the class

CReport the_object;

This together with a read(descriptor, Buffer, BUFFER_SIZE) call spoils the
stack and the bug then starts to emerge at many different places.
If the read() is never called, the stack gets not spoilt.

What didn't help was moving the object as a whole from the stack to the
heap, i.e. using:

CReport *the_object_ptr;
  the_object_ptr = new CReport;

instead of the:

CReport the_object;

What finally did help was allocating also the buffer itself dynamically,

class CReport {
  char *Buffer
void CReport::CReport() {
  Buffer = (char*) malloc(BUFFER_SIZE*sizeof(char));

Many thanks to everybody for all the hints.


mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe

More information about the users mailing list