0

I am trying to figure out, why my char* const isn't new and empty?

char* const a = new char[10];

Gives me:

\r\r\r�����������

EDIT: Ran a test,

std::string text = "Hello world!";
int length = text.size();
char* const a = new char[length];
std::memset(a, '\0', length);
std::strncpy(a, s.c_str(), length); // <-- after this, the gibberish comes back.
pptaszni
  • 5,591
  • 5
  • 27
  • 43
John Smith
  • 465
  • 4
  • 15
  • 38
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/220824/discussion-on-question-by-john-smith-array-allocated-like-char-const-pointer-gi). – Machavity Sep 02 '20 at 00:31

1 Answers1

4

why my char* const isn't new and empty?

Because you didn't create an empty array, but an array of size 10. Therefore there are 10 elements.

Furthermore, you didn't initialise any of the elements. More specifically, you didn't initialise any of the elements to be the null terminator character. As such, your array is not guaranteed to contain a null terminated string, and therefore inserting it into a character stream results in undefined behaviour.

You can initialise all of the elements to be null terminators by using value initialisation:

 char* const a = new char[10]();

Or you could do it only for the first element:

a[0] = '\0';

Or you could create an empty std::string:

std::string a;
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Sorry, but I am getting: `½½½½½½½■ε■ε■` this doesn't work. – John Smith Sep 01 '20 at 14:10
  • @JohnSmith I'm not getting that. There is probably something wrong with your program. – eerorika Sep 01 '20 at 14:11
  • @JohnSmith show us also how you are printing the content of that array and maybe the whole declaration, memsetting/initialization and printing by editing your question – John Doe Sep 01 '20 at 14:12
  • 1
    @JohnSmith This answer is correct. If you get different results then there is another problem with your code that is shown in the question. Please read about [MCVE]s. – François Andrieux Sep 01 '20 at 14:13
  • This fixed it for me, `std::memset(a, '\0', length);`. – John Smith Sep 01 '20 at 14:25
  • 1
    @JohnSmith `memset` isn't necessary for a zero initialized array: https://wandbox.org/permlink/JOG5MZVnUdkcdwW4 You have another problem in your code. – Thomas Sablik Sep 01 '20 at 14:28