babybob
babybob

Reputation: 444

C Program terminated only after it has executed in GCC

I intentionally made an out of bound index access in my program which is given below :

#include<stdio.h>

int main()
{
    int x[1];

    x[1] = 3; // expected SIGABRT here
    printf("x[1] = %d\n",x[1]);

    return 0;
}

But my program got terminated only after the execution of the line where I was expecting a abort. The same happened when I debugged. Find the output below.

x[1] = 3
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

I know that C doesn't have out of bound checking feature. My question is why it didn't terminate after the execution of x[1] = 3 without going for the next statement ?

Upvotes: 1

Views: 232

Answers (1)

4386427
4386427

Reputation: 44274

I assume that this is about using a canary value to detect attempts of exploiting a stack buffer overflow.

The stack (aka the canary value) isn't checked until the function returns. Therefore you'll get the printf executed first and then the stack check is performed.

In other words, the "out of bounds" access isn't detected the moment it happens. So the program carries on until the function returns.

You could put the offending code into a function like:

void foo()
{
    int x[1];

    x[1] = 3; // expected SIGABRT here
    printf("x[1] = %d\n",x[1]);
}

int main()
{
    foo();
    printf("Back in main\n");
    return 0;
}

to see if the program terminates before printing "Back in main"

Upvotes: 5

Related Questions