Search code examples
c++memory-managementc++17

why allocating char on the free store giving wrong value?


I'm allocating memory on the free store and putting the char on that storage, but it giving some unexpected output in long input of char, and on my pc it giving me unexpected result for more than even 1 char of input, but if i comment out delete [] p; in add_char(), it give expected result.

that's what im getting on my pcsee demo on godbolt

#include <iostream>
#include <cstring>


char* add_char(char* p, char ch) 
{
    char* pc = new char[strlen(p) + 1];

    for (size_t i = 0; i <= strlen(p); ++i) {
        if (i == strlen(p))
            pc[i] = ch;

        else
            pc[i] = p[i];
    }

    delete[] p;
    return pc;
}
int main()
{
    char ch = 0; 
    char* pc = new char[1]{'a'};

    while (std::cin >> ch && ch != '!') {
        pc = add_char(pc, ch);

    }
    std::cout << "pc : " << pc << "\n";
    std::cout << strlen(pc) << "\n";;
}

Solution

  • strlen relies on null character \0 to calculate the length of the given string, so you have to provide it for both initial value:

    char* pc = new char[]{'a', '\0'};
    

    ..and keep it while appending the inserted characters one by one:

    const std::size_t newLength = strlen(p) + 2; // +1 for null terminator (strlen ignores) and +1 for new character
    char* pc = new char[newLength];
    
    
    for (size_t i = 0; i < newLength; ++i) {
        if (i == newLength - 1)
            pc[i] = '\0';
        else if (i == newLength - 2)
            pc[i] = ch;
        else
            pc[i] = p[i];
    }
    

    P.S. alternatively you can drop use of strlen and keep the array length elsewhere