Posts

Showing posts from April, 2025

Reasons for Stack Corruption in a C Program

  Reasons for Stack Corruption in a C Program Stack corruption occurs when a program writes outside the boundaries of the allocated stack memory, leading to unpredictable behavior, crashes, or security vulnerabilities. Here are the main causes: 1. Buffer Overflow (Writing Past Array Bounds) Writing beyond the allocated size of an array can overwrite adjacent stack memory. Example: #include <stdio.h> void badFunction() { char buffer[10]; for (int i = 0; i < 20; i++) { // Writing beyond buffer size! buffer[i] = 'A'; } } int main() { badFunction(); return 0; } 🔴 Risk : Overwrites return addresses, local variables, or function parameters. 2. Incorrect printf Format Specifiers Using %s with a non-string value or forgetting to pass arguments correctly can lead to undefined behavior. Example: #include <stdio.h> int main() { int num = 123; printf("%s", num); // Wrong: passing an integer instead of a stri...