|
-
April 4th, 2012, 07:00 PM
#1
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 . But i have no clue why. Why do i get this error?
-
April 4th, 2012, 09:47 PM
#2
Re: Strcpy/memory allocation problem
 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
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
Last edited by Paul McKenzie; April 4th, 2012 at 09:51 PM.
-
April 5th, 2012, 05:06 AM
#3
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
-
April 5th, 2012, 05:40 AM
#4
Re: Strcpy/memory allocation problem
Have a look in MSDN Library, at Security Enhancements in the CRT.
-
April 5th, 2012, 05:59 AM
#5
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
-
April 5th, 2012, 06:16 AM
#6
Re: Strcpy/memory allocation problem
 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()
Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
Convenience and productivity tools for Microsoft Visual Studio:
FeinWindows - replacement windows manager for Visual Studio, and more...
-
April 5th, 2012, 06:20 AM
#7
Re: Strcpy/memory allocation problem
Great suggestion. Thanks!
-
April 5th, 2012, 06:34 AM
#8
Re: Strcpy/memory allocation problem
 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...
Last edited by ovidiucucu; April 5th, 2012 at 06:57 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|