Hello, you are using an old browser that's unsafe and no longer supported. Please consider updating your browser to a newer version, or downloading a modern browser.

Global Accelerated Learning • Est. 1999
Glossary Term Stack Canary

Training Camp • Cybersecurity Glossary

What is Stack Canary?

A random guard value placed before a function's return address; if a buffer overflow corrupts it, the program aborts before hijacking control flow.

Glossary > Application & API Security > Stack Canary

Stack Canary — A random guard value placed before a function's return address

Understanding Stack Canary

A stack canary is a memory-protection mechanism that defends against stack-based buffer overflow attacks. The compiler inserts a secret, random value (the canary) between a function's local buffers and its saved return address. Before the function returns, the code verifies the canary is unchanged; if an overflow overwrote it, the program aborts instead of jumping to attacker-controlled code.

The mechanism works because a contiguous overflow that reaches the return address must first overwrite the canary sitting in front of it. At function entry, the prologue copies a per-process random value (often stored in thread-local storage and seeded at startup) onto the stack. The epilogue compares the on-stack copy against the reference; a mismatch calls an abort handler like __stack_chk_fail. Compilers enable this via flags such as GCC/Clang's -fstack-protector and -fstack-protector-strong.

This matters because stack overflows have historically been one of the most reliable paths to remote code execution. By turning a silent memory corruption into a controlled crash, canaries raise the cost of exploitation significantly, especially when combined with ASLR and non-executable stacks (NX/DEP). Without them, a single unchecked strcpy into a fixed buffer can let an attacker overwrite the return address and seize control of the process.

For example, suppose a network daemon copies untrusted input into a 64-byte stack buffer with no bounds check. An attacker sends 200 bytes to overwrite the return address with the location of injected shellcode. With stack canaries enabled, those 200 bytes also clobber the canary; on return, the verification fails, __stack_chk_fail terminates the process, and the exploit becomes a denial of service rather than a system compromise. Attackers must then leak or guess the canary, which is much harder than a blind overflow.

Learn More About Stack Canary:

Ready to Get Certified?

Turn knowledge into credentials with our instructor-led cybersecurity boot camps.

View All Courses →