Heap Spraying Examples: The Art of Filling the Stack

A Crash Course

Heap spraying, or heap smashing, is a fun technique used to crash programs by overloading the memory heap with junk data.

Example 1: The Classic

Here's an example of heap spraying in C:

      
#include<stdio.h>

int main() {
  char *heap = alloca(1024 * 1024);
  *heap = 'x'; /* trigger the overflow */
  return 0;
}


    

Example 2: The More Complex One

This one's a bit more advanced:

      
#include<stdio.h>

int main() {
  char *heap = alloca(1024 * 1024);
  int i;
  for (i = 0; i < 1024; i++) {
    heap[i] = 'x';
  }
  return 0;
}


    

Want more? Check out our Heap Spraying Theory subpage for a deeper dive.

Or maybe you'd rather learn about Practical Heap Spraying?