strncpy copying beyond max length

A

atapi103

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.
 
P

Pete Becker

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.
 
A

atapi103

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.
 
D

Dave Moore

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top