Skip to content
Advertisement

C – How can a pointer overwrite a local const block of memory but not the global const block of memory?

Last time I asked how can I generate segmentation fault in a program by bypassing the compiler’s promise of not overwriting the const memory. User Marco Bonelli described the following way, which worked perfectly.

const static int global = 123;

int main(void) {
  int *ptr = (int *)&global;
  *ptr = 456;

  // or, equivalent
  const int *ptr2 = &global;
  *(int *)ptr2 = 456;
}

Either way I was able to generate segmentation fault.

  • int *ptr = (int *)&global;
    *ptr = 456;
    
  • const int *ptr2 = &global;
    *(int *)ptr2 = 456;
    

Now my question is what is it that is preventing the pointer from writing to a global const block of memory but not to the local const block of memory. For example, in the below code I was able to write to the const block of memory without any issue.

#include <stdio.h>

int main(void) {
  const int local = 123;
  
  int *ptr = (int *)&local;
  *ptr = 456;
  
  // how come this be possible?
  printf("%dn", local); // -> 456

  // or, equivalent
  const int *ptr2 = &local;
  *(int *)ptr2 = 512;

  // how come this be possible?
  printf("%dn", local); // -> 512
}

I’m curious about knowing how this happened. Please enlighten me.

If it matters, I’m using gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0.

Advertisement

Answer

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement