jayer
jayer

Reputation: 51

Don't understand this behaviour: changing the value that a pointer points to causes the pointer value itself to change in C?

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

Answers (1)

hyde
hyde

Reputation: 62908

You need to have space for the canary:

char buf[8+sizeof(int)];

Upvotes: 1

Related Questions