Search code examples
cmemory-managementheap-memoryvirtual-memorystack-memory

Causing a seg fault in C | Heap stack virtual memory


#include <stdio.h>

int main() {
  char *ptr;

  while(1){ 
    ++ptr; 
    printf("%p\n", ptr); 
  }
  return 0;
}

Question: Your code should increment a pointer that points at the heap, by 1 byte, repeatedly, until the program crashes.

I'm trying to create a segfault by iterating over all addresses in the stack, one byte at a time. However, the code just keeps running and doesn't cause a segmentation fault. How could I change it to cause a segfault?


Solution

  • To get a pointer that points to the stack, set it to the address of a local variable:

    int main() {
        int object;
        int *p = &object;
    

    However, simply incrementing a pointer will not cause a segmentation fault. To get a segmentation fault you need to dereference an invalid pointer. So the loop should be like:

        while(1) {
            ++ptr;
            printf("%p %d\n", ptr, *ptr);
        }
    

    Trying to print *ptr will eventually cause the fault.

    For the heap you can do it similarly, but initialize p with a call to malloc() instead of the address of a local variable.