First element of a pointer is polluted C++

Viewed 59

I have this piece of code that puts a random string in an char pointer array:

char * str[100] = {0};
const int elems = sizeof(str)/sizeof(str[0]),size=5;

srand(time(0));

for(int i=0;i<elems;i++){
    char rString[size] = {0};
    for(int j = 0;j<size;j++){
        rString[j] = 97+rand()%26;
    }
    rString[size] = '\0';
    str[i] = new char[size];
    strcpy(str[i],rString);
}

for(int i=0;i<elems;i++){
    cout<<str[i]<<endl;
}

But str[0] is polluted or empty.

1 Answers

Your rString[size] = '\0'; writes to an element out of bounds! The last element is rString[size-1]. Anything after this will be undefined behaviour.

To fix this (but keeping 5-character strings), you need to increase size to 6 and change your loop limits and null-terminator index, as follows:

int main()
{
    char* str[100] = { 0 };
    const int elems = sizeof(str) / sizeof(str[0]), size = 6; // Add space for nul-terminator
    srand(time(0));
    for (int i = 0; i < elems; i++) {
        char rString[size] = { 0 };
        for (int j = 0; j < size-1; j++) { // End BEFORE last character
            rString[j] = 97 + rand() % 26;
        }
        rString[size-1] = '\0'; // Last element is at [size-1] NOT [size]
        str[i] = new char[size];
        strcpy(str[i], rString);
    }
    for (int i = 0; i < elems; i++) {
        std::cout << str[i] << std::endl;
    }
    // And, for good measure, don't forget to free the allocated strings:
    for (int i = 0; i < elems; i++) {
        delete[] str[i];
    }
    return 0;
}

Alternatively (if you insist on using raw pointers and C-style strings), you can just change your rString declaration and str[i] allocation lines to use size+1 (less typing):

//...
    char rString[size+1] = { 0 };
   //...
    str[i] = new char[size+1];

But you really should consider using more modern C++ techniques, like std::string and std::vector, in place of your dynamic arrays. Here's a version using those STL containers:

int main()
{
    std::vector<std::string> str(100);
    const int elems = str.size(), size = 5;
    srand(time(0));
    for (int i = 0; i < elems; i++) {
        std::string rString {""};
        for (int j = 0; j < size; j++) {
            rString += static_cast<char>(97 + rand() % 26);
        }
        str[i] = rString;
    }
    for (int i = 0; i < elems; i++) {
        std::cout << str[i] << std::endl;
    }
    return 0;
}

Feel free to ask for further clarification and/or explanation.

Related