0

I am having some trouble understanding this output for my code:

#define MAX 5

char pipeNames[MAX][1024];
string s1 = "\\\\.\\p\\p1";
string s2 = "\\\\.\\p\\p2";
int len1 = strlen(s1.c_str());
int len2 = strlen(s2.c_str());
memcpy((void*)pipeNames[0], (void*)s1.c_str(), len1);
memcpy((void*)pipeNames[1], (void*)s2.c_str(), len2);
cout<<pipeNames[0];
cout<<endl<<len1;
cout<<endl<<pipeNames[1];
cout<<endl<<len2;

Actual Output:

\\.\p\p1É┼é|
8
\\.\p\p2
8

Expected Output:

\\.\p\p1
8
\\.\p\p2
8

Why are the extra characters being printed at the end of pipeNames[0]. I am using string::c_str() which automatically appends null character, so why the error?

Shailesh Tainwala
  • 6,299
  • 12
  • 58
  • 69

2 Answers2

2

You're not copying the null char. strlen does not count the null char. Try this

memcpy(pipeNames[0], s1.c_str(), len1 + 1);
memcpy(pipeNames[1], s2.c_str(), len2 + 1);

No need for your casts either. Casts are dangerous, because they can mask compiler errors so don't use them if you don't need them.

jahhaj
  • 3,021
  • 1
  • 15
  • 8
2

This would be better

memcpy((void*)pipeNames[0], (void*)s1.c_str(), len1 + 1);
                                                      ^
memcpy((void*)pipeNames[1], (void*)s2.c_str(), len2 + 1);
                                                      ^

to ensure that you null terminate the copied string. Your initial array is not initialised, so the data in your array could be anything to start with - so if it was not a zero, your print functions will just carry on outputting until they DO find a null char.

Even better as one of your comments suggests, use strcpy instead

mathematician1975
  • 21,161
  • 6
  • 59
  • 101