Search notes:

gcc -fsanitize=address

Detecting a stack overflow

The following program uses the preprocessor macro ALLOCATION_SIZE to specify at compile time how many bytes will be written in the function write_buffer to a buffer allocated on the stack in the function func:
//
//   TODO: See https://github.com/google/sanitizers/wiki/AddressSanitizer
//

#include <stdio.h>


int write_buffer(char* buf, unsigned int size) {
   for (unsigned int pos=0; pos < size; pos++) {
      buf[pos] = (char) pos;
   }
}

int func() {
   char buf[20];
   write_buffer(buf, ALLOCATION_SIZE); // Uh, oh.

   return 42;
}

int main() {
   printf("ALLOCATION_SIZE = %d\n", ALLOCATION_SIZE);
   printf("func returned %d\n", func());
   printf("\n\n");
}
Github repository about-gcc, path: /options/f/sanitize/address/prog.c
Because the size of the buffer is limited to 20 bytes, the program exhibits a stack overflow if ALLOCATION_SIZE is greater than 20.

Makefile

This Makefile creates two programs, prog-ok where ALLOCATION_SIZE is set to 20 and prog-stack-overflow where ALLOCATION_SIZE is set to 21, and runs them.
.PHONY: run

run: prog-ok prog-stack-overflow
	./prog-ok
	./prog-stack-overflow

prog-ok: prog.c
	gcc -DALLOCATION_SIZE=20 -fsanitize=address $< -o $@

prog-stack-overflow: prog.c
	gcc -DALLOCATION_SIZE=21 -fsanitize=address $< -o $@
Github repository about-gcc, path: /options/f/sanitize/address/Makefile
Because -fsanitize=address is set, it is possible to determine where the stack overflow took place.

See also

GCC options such as -f ….

Index