Reputation: 51
My goal is to write a canary-like mechanism to detect overflow in a character buffer. What I'm trying to do is to get the address of the end of the buffer and place a canary there, so that writing past the buffer would cause the canary value to change. After some debugging, I found that a problem is when I write a value to the address, the value of the address itself changes unexpectedly. Can anyone explain why this happens?
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand(time(NULL));
int secret = rand();
char buf[8];
char *aft_buf = buf + 8;
printf("aft buf address = %p\n", aft_buf);
int *canary = (int *) aft_buf;
*canary = secret;
printf("canary address = %p\n", canary); // this value becomes different from aft_buf. why?
return 0;
}
I'm compiling with gcc -fno-stack-protector
, and I don't get this problem when I compile with -O2
flag.
Upvotes: 0
Views: 58