Home > Mobile >  String stores data from unrelated memory address
String stores data from unrelated memory address

Time:12-23

I'm trying to generate a string of 50 dots. I have the following code:

#include <string>

using namespace std;

int main(){
  string s(".",50);
  cout << s;
  }

and the output is:

.vector::_M_realloc_insert$C����pX�%

The string s doesn't store . 50 times, but some other part of memory. A leak happened, and I have no idea how.

What went wrong? How do I go about generating a string of length n consisting only of dots? In general, I want to do in c what in python would be done by "c"*n.

Thank you.

CodePudding user response:

Your example could be a whole lot shorter, and still have the same problem.

The problem is that with the std::string constructor you use, the length is the length of the string ".", not how long the std::string should be. Since "." is not 50 characters long, you will have undefined behavior.

From the linked reference for constructor number 4 (the one you use):

The behavior is undefined if [s, s count) is not a valid range

There s is the string "." and count is the value 50.

The constructor I guess you want to use is the one taking a single character instead of a string (number 2 in the linked reference):

std::string s(50, '.');  // Fill string with 50 dots
  • Related