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:
Code:
#include <iostream>
char * exp_str( void );
int main ( int argc, char **argv )
{
char * pword = new char;
strcpy_s( pword, 1024, exp_str( ) );
return 0;
}
char * exp_str( void )
{
static char word[1024];
strcpy_s( word, 1024, "testing!" );
return word;
}
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:
Code:
#include <iostream>
char * exp_str( void );
int main ( int argc, char **argv )
{
char * pword = new char;
printf("");
strcpy_s( pword, 1024, exp_str( ) ); // Only works with the printf("")
return 0;
}
char * exp_str( void )
{
static char word[1024];
strcpy_s( word, 1024, "testing!" ); // Always works.
return word;
}
Compiles & Executes without error on my computer.
My goal was to copy the contents of one string pointer to another, as the first pointer's contents change pretty often...
I'm not married to this method, but was hoping to write a temp-function until I can better grasp C++ strings... however my question to you guys is: Can anyone explain to me why that works?