By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,389 Members | 1,881 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,389 IT Pros & Developers. It's quick & easy.

strncpy copying beyond max length

P: n/a
I am quite new to C++ and am haveing dificulty with the strncpy
function. I wrote this peice of code but the output I get from the
destination string after the copy is not what I expected, instead it
leaks into the memory space of string 1. Here is the output and the
code, Im hopeing someone can point me in the correct direction to solve
this problem:

const int MAX_STRING = 5;
char str1[] = "Hello, world!";
char str2[MAX_STRING+1]; // include room for null
strncpy(str2, str1, MAX_STRING);
cout << "String1: " << str1 << endl;
cout << "String2: " << str2 << endl;

output: Hello -w 3-wHello, world!

I was wanting to set string 2 to Hello but instead I got much more then
5 characters.

Jul 23 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
at******@gmail.com wrote:

I was wanting to set string 2 to Hello but instead I got much more then
5 characters.


strncpy only copied five characters. There's a catch, though. Read the
documentation for strncpy carefully.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #2

P: n/a
Thanks, I have located the documentation and read it carfully and I can
now see the problem is a null was not appended because the value was
shorter then the length of the string being copyed thus i must apend my
own terminateing null caracter.

Much apreciation for this, I will read the documentation first for now
on. My book stated that it apends the null for me and I guess I asumed
this to be corect.

Problem solved.

Jul 23 '05 #3

P: n/a
at******@gmail.com wrote:

My book stated that it apends the null for me and I guess I asumed
this to be corect.


Sounds like a good book to get rid of. <g>

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #4

P: n/a
If you really want to use C++ properly, you should generally learn to use
string objects instead of char arrays. All these problems you are having
with string length and null termination are handled in a completely
transparent fashion by the standard C++ string class. Sounds nice doesn't
it? 8*)

HTH,

Dave Moore
Jul 23 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.