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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1743264594, '3.131.142.67', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/C-C-plus-plus/GCC/options/f/sanitize/address(89): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78