Strcpy/memory allocation problem
Code:
char str[]="Hello"; // 5 chars
char *tmpstr;
int size = strlen(str); // 5
tmpstr = new char[size+1]; // char[6]
strcpy_s(tmpstr, size, str); <error
tmpstr[size]=0;
results in http://img7.imagebanana.com/img/oecrhr95/Unbenannt.PNG. But i have no clue why. Why do i get this error?
Re: Strcpy/memory allocation problem
Quote:
Originally Posted by
ImNotaBot
Why do i get this error?
Code:
tmpstr = new char[size+1]; // char[6]
strcpy_s(tmpstr, size, str); <error
http://msdn.microsoft.com/en-us/libr...7;28v=vs.90%29
Quote:
The strcpy_s function copies the contents in the address of strSource, including the terminating null character, to the location specified by strDestination.
Regards,
Paul McKenzie
Re: Strcpy/memory allocation problem
Okay thankyou for the fast reply. But for what reason do I have to state the size of the source string? (2nd parameter)
Greets
Re: Strcpy/memory allocation problem
Have a look in MSDN Library, at Security Enhancements in the CRT.
Re: Strcpy/memory allocation problem
Ahh untill now i thought, that the new secure functions work in a different way. In case if strcpy_s i thought just <size> characters would be copied. Well, I see no gain in there, hence i wont use them anymore... i guess strncpy is my friend.
Thanks a lot for the enlightment :-D
Re: Strcpy/memory allocation problem
Quote:
Originally Posted by
ImNotaBot
i guess strncpy is my friend
If you are looking for a friend, check out strncpy_s :)
But to make a copy of a string, use strdup()
Re: Strcpy/memory allocation problem
Great suggestion. Thanks!
Re: Strcpy/memory allocation problem
Quote:
Originally Posted by
ImNotaBot
Ahh untill now i thought, that the new secure functions work in a different way. In case if strcpy_s i thought just <size> characters would be copied. Well, I see no gain in there, hence i wont use them anymore... i guess strncpy is my friend.
That makes sense to avoid buffer overrun in case you pass a larger source or some non nul-terminated garbage.
If a "_s function" didn't pass the run-time tests, it shows you that something is wrong with your program, while "your friend" strncpy doesn't.
See also these articles:
[ Later edit ]
And of course, as Vlad already stated, strncpy_s may be an even better friend... :)