Monday, March 9, 2020

Stack corruption due to different pointer types

The C programming language allows you to send a float pointer to a function that expects a double pointer, which causes stack corruption. Example code:
//Stack corruption due to different pointer types.
//Note1: This code only builds in C. C++ compiler does not build it.
//Note2: You will see the stack corruption message only when building in debug mode. In release mode, you won't see an error message.
//Şamil Korkmaz, March 2020
#include<stdio.h>
void fun(double *val_d) { //double pointer
*val_d = 5;
}
int main() {
float val_f1 = 1;
double val_d = 2;
val_f1 = val_d; //Assigning a double to a float does not cause problems (as long as double value is small enough to fit into float)
printf("val_f1: %1.3f\n", val_f1);
float val_f2 = 10;
fun(&val_f2); //Sending float pointer to a function that expects double pointer which causes stack corruption.
printf("val_f2: %1.3f\n", val_f2);
printf("Press enter...\n");
getchar();
}
When you run it, you will see that the val_f2 is zero (should be 5):

Visual Studio 2015 will only display stack corruption message when you build in debug mode. In release mode, you don't get a message.

If you copy the same code to a cpp file, Visual Studio will use the C++ compiler and it will not build the code, saying that types are incompatible.

No comments:

Post a Comment