cookya
cookya

Reputation: 3307

"Program received signal SIGABRT, Aborted" - Why?

Please help me understand - why am I getting this run-time error:

*** stack smashing detected ***:
Program received signal SIGABRT, Aborted.

for the following code :

#define WORD_SIZE   (sizeof(int))
#define FLOOR_MASK  0xfffffffc


static void SetVal(void* _block, int _size)
{
    *(int*)_block = _size;
}

void BufferInit(void* _buffer, size_t _totalSize)
{
  int alignedSize;

  assert(_buffer);

  /* align _totalSize to be WORD_SIZE multiple */
  alignedSize = _totalSize & FLOOR_MASK;

  /* mark end of buffer */
  SetVal(_buffer + alignedSize, END_VAL);
}

int main()
{
    Byte buffer[36];

    BufferInit(buffer, 37);

    return 0;
}

P.S: The error occurs at the end of the run (on line "return 0;" ).

Thanks.

Upvotes: 0

Views: 13905

Answers (2)

cookya
cookya

Reputation: 3307

Stupid mistake..

I exceeded buffer's size:

alignedSize [= buffer size] = 36
bytes allocated for buffer:   0-35

I'm changing (buffer+36) = buffer[36] which is beyond buffer's memory limit.

Fixed code:

SetVal(_buffer + alignedSize - WORD_SIZE, END_VAL); 

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129524

The SetVal() function writes to 4 bytes to the location you have indicated as the end. That is:

BufferInit(buffer, 37);

... Leads to ... 

SetVal(_buffer + alignedSize, END_VAL);

... which does ...

*(int*)_block = _size;

alignedSize is 36 (37 & ~3 = 36) [~3 = 0xFFFFFFFC]. 4 bytes at offset 36 writes to bytes 36, 37, 38 and 39. Since your buffer originally is 36 bytes long, it's outside of your buffer. Either change your buffer to be 40 bytes long, or change your 37 to be 33 [or a lower number].

Upvotes: 3

Related Questions