I have a C++ function that is supposed to repeat a string a certain amount of times. What I've seen is that when the resulting string is more than 15 characters long, the function does not return anything, but it works as expected when the string is less than 16 characters long.
Here is the function:
const char* repeat(const char* str, int n) { std::string repeat; std::string s=std::string(str); for (int i = 0; i < n; i++) { repeat += s; } printf(repeat.c_str()); // this is for testing printf("\n"); return repeat.c_str(); // It returns the same thing it prints } When using gdb, the output of the function is like this: (I added comments)
(gdb) print repeat("-",10) ---------- // prints 10 dashes $1 = 0x7fffffffd9e0 "----------" // returns 10 dashes (gdb) print repeat("-",15) --------------- // prints 15 dashes $2 = 0x7fffffffd9e0 '-' <repeats 15 times> // returns 15 dashes (gdb) print repeat("-",16) ---------------- // prints 16 dashes $3 = 0x5555555712c0 "" // returns nothing (gdb) print repeat("-=",8) -=-=-=-=-=-=-=-= // prints 8 "-="s $4 = 0x5555555712c0 "" // returns nothing (gdb) I have no idea what this is about.
PS: this is my first SO post so I'm not used to doing this.
Update
My understanding of C strings was wrong, I still don't fully understand them so I will stick to std::string. Returning const char* was the wrong thing because it returns a pointer to something only to be used once. This is my new code:
std::string repeat(std::string str, int n) { std::string repeat; for (int i = 0; i < n; i++) { repeat += str; } return repeat; } Thanks for the help!
c_strreturns a pointer to thestd::strings internal buffer. The function returns a dangling pointerstd::string? Your function only returns a pointer. Pointers point somewhere. To store a string you need a string, not just a pointerconst char* repeat(const char* str, int n). It returns a pointer. The pointer should be pointing to some memory. Where does this memory come from? When is it created? When is it destroyed? Who is responsible for destroying it? If you cannot answer these questions, don't start writing the function. Crack open a textbook instead.