char *buffer = new char[14];
unsigned fileSize = (unsigned)(width*height*4 + 54);
for(int i = 0;i < 40;i++)
buffer[i] = 0;
Here your are allocating the buffer of 14 char. While in loop you are filling the buffer for 40 iterations. It is "Array out of Bound" memory corruption.
It's just luck that is not crashing with VC++