1

I am no C programming expert, But here is a piece of code which i am working on

static char gszBuf[10] ="1234567890";
#define       LS_MAX_STRING    255
LoadDatatoBuffer(id, gszBuf, LS_MAX_STRING); 
// this method will load the data wrt ID to gszBuf

Considering that the above method loads a char string having more than 10 characters, i.e. gszBuf = "abcdefghijklmnopqr";

The above code will run without any issue in msdev 6.0. but the same application created using visual studio 2010 crashes when we try to copy the above data. My question is what made the above code to work in msdev 6.0 and why couldnt it run in visual studio 2010

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
Lets Code
  • 42
  • 2
  • 5
  • I'd say it was because VS2010 has implemented some array bounds checking which wasn't present in MSDEV 6.0. I had a quick search but not spotted anything to confirm this though. – ChrisF Nov 24 '15 at 11:47
  • 1
    Oh, and the code wasn't working in MSDEV 6.0. It was overflowing the buffer causing undefined behaviour. – ChrisF Nov 24 '15 at 11:53
  • But when in try to disply the value in gszBuf, it displays the proper value which is more than 10 characters in MSDEV 6.0 – Lets Code Nov 24 '15 at 12:10
  • 2
    Everything could happen if you have Undefined behavior in your program. Examples: it will work fine, or it will work fine sometimes, or it will explode universe, or it will make your cat pregnant,... The fact that you have correct values somewhere sometimes does not prove your program is correct. Most of the times those are pointer issues, out of bounds array accesses, stack buffer overruns, heap corruptions etc.The root of all evil things in your application is that you are trying to write C in C++. And C is hard. – Ivan Aksamentov - Drop Nov 24 '15 at 12:17

2 Answers2

1

You should be grateful that VS2010 made your code "crash".
When you have buffer overruns, it's better to crash as soon as possible, instead of letting hackers exploit your buffer overflow.

There are several security improvements and buffer overflow checks with VS2010: consider them opportunities to improve the quality of your code and fix buffer overrun related bugs.

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
0

Undefined behavior can mean that the code will crash, but may mean that the code appears to work, but causes failure.

In this case, if gszBuf is at beginning of a CPU page, and after it, nothing is important, then it won't crash.

mksteve
  • 12,614
  • 3
  • 28
  • 50