简体   繁体   中英

Error "stack smashing detected" while prepending line numbers in a string

I'm taking a string as input for the function, and I'm trying to prepend line numbers to every new line in the string. I'm also returning a string but it keeps giving me this error: stack smashing detected .

Here's the code:

string prepend(string code) {
    string arr;
    int i = 0;
    int j = 0;
    int count = 100;    
    while (code[i] != '\0') {
        if (j == 0) {
            arr[j] = count;
            arr[j + 3] = ' ';
            j = j + 4;
        }
        if (code[i] == '\n') {
            arr[j + 1] = count;
            arr[j + 3] = ' ';
            j = j + 4;
        }
        arr[j] = code[i];
        i++;
        j++;
        count++;
    }
    
    return arr;
}

There are several errors in your code,

  1. you should convert int to string using to_string()
  2. you should iterate string using its size() ...
#include <iostream>
#include <string>

using namespace std;

string prepend(string code) {
    string arr;
    int count = 1;
    arr += to_string(count++) + " ";
    for (size_t i = 0; i < code.size(); ++i) {
        arr += code[i];
        if (code[i] == '\n') {
            arr += to_string(count++) + " ";
        }
    }
    return arr;
}

int main(int argc, char **argv) {
    string code = "a\nbc\nd ef g\n\n";
    cout << prepend(code);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM