Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ function doesn't return anything more than 15 characters

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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!

>Solution :

You are invoking UB (Undefined Behavior) by returning a pointer into a string (repeat) that is locally declared and therefore de-allocated when your function returns. I’d suggest that you have your function actually return the string object itself instead of const char*.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading