I am doing some experiments with GCC's stack protection feature to understand it better. Basically I referred to this post on stackoverflow.
The following is my code.
test.c
#include <stdio.h>
void write_at_index(char *arr, unsigned int idx, char val)
{
arr[idx] = val;
printf("\n%s %d arr[%u]=%d\n", __func__, __LINE__,
idx, arr[idx]);
}
void test_stack_overflow()
{
char a[16] = {0}; //Array of 16 bytes.
write_at_index(a, 30/*idx*/, 10/*val*/); //Ask the other function to access 30th index.
printf("\n%s %d Exiting a[0] %d\n", __func__, __LINE__, a[0]);
}
int main()
{
test_stack_overflow();
return 0;
}
The following is my makefile.
Makefile
CC=gcc
BIN=./test.out
SRCS=./test.c
all: $(BIN)
OBJ = ${SRCS:.c=.o}
CFLAGS=-O0 -fstack-protector -fstack-protector-all
$(OBJ): %.o: %.c
$(CC) $(CFLAGS) $(INCLUDES) -c $*.c -o $*.o
$(BIN): $(OBJ)
$(CC) -o $@ $<
rm -rf ./*.o
clean:
rm -rf ./*.out
rm -rf ./*.o
I am using gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
When I build and run test.out, I get " stack smashing detected " crash as expected.
However, if I change optimization level to O3, (CFLAGS=-O3 -fstack-protector -fstack-protector-all)
and build and execute test.out, I am not observing the crash.
So my question is, does the compiler remove the "-fstack-protector" option when optimization is enabled? Or am I missing some other setting here?