C++ (char *) problem?

I've been slowly teaching myself C++ and haven't gotten around to the String class just yet. I'm working under Vista Business (laugh if you must) and Visual Studio 2005 (again).

When attempting to use (something a tad more familiar to me) strcpy() in VS05 I quickly was presented with the "Safer" alternative, strcpy_s() - after switching over to it I've got some concerns... no longer does my program crash after a lengthy run time, but after copying only two strings! (previously it was copying somewhere in the vacinity of 148 strings successfully.) I was wondering exactly what made it crash, so I setup a test program, which pretty much emulates what I'm trying to do:

Compiles fine, but didn't work, popped out of Vista with a "Test Program.exe has stopped working..."

Tried to trace where it was failing, so I interjected some printf() statements.. and all of a sudden it was working, without altering a single line of the other code. So I spent a little time and found my solution:

This is undefined behavior. You allocate one char, but set buffer size to 1024? You're pretty much negating the use of strcpy_s. Specify proper or real buffer size. It should then assert if you try to copy too much data.

Originally Posted by Adak

io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

Originally Posted by Salem

You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

Resolved, thanks. -- Still curious though, why would the printf(""); make it work?

Because the program with the printf("") is a different program than one without it. Things were arranged differently in memory in a way that concealed your bug. Also, adding a function call can change the effects of an uninitialized-local-variable bug.