Search code examples
c++arraysruntime-errorc-stringsstrcpy

Visual studio Run-Time Check Failure #2 - Stack around the variable 'temp' was corrupted


I've written a function to partition elements for a quick sort algorithm for sorting an array of cstrings

void partition(char words[][MAXWORDLEN + 1], int start, int end, int& partitionIndex) {
char pivot[MAXWORDLEN + 1]; //choose last element to be the pivot
strcpy(pivot, words[end]);
partitionIndex = start; //partition index is initalized to the first index
for (int i = start; i < end; ++i) { //iterate through the array
    if (strcmp(words[i], words[end]) < 0) {
        char temp[MAXWORDLEN];
        strcpy(temp, words[i]); //swap the element with the element corresponding to the partition index
        strcpy(words[i], words[partitionIndex]);
        strcpy(words[partitionIndex], temp);
        partitionIndex++;
    }
}
cout << end << endl;
char temp[MAXWORDLEN + 1];
strcpy(temp, words[end]);
strcpy(words[end], words[partitionIndex]);
strcpy(words[partitionIndex], temp);

}

However, when I run the program, I get a run time check failure. MAXWORDLENGTH is 6 and all words in the array are between 4-6 characters long. So I'm confused why the variable temp can't seemed to be copied to words at index partitionIndex


Solution

  • Change this:

    char temp[MAXWORDLEN];
    

    to this:

    char temp[MAXWORDLEN + 1];
    

    since the pivot array has this size too.


    So when temp was of size 6 and the word it contains had 6 characters, the null terminator would be overwritten, meaning that the copy would fail and invoke Undefined Behavior. We don't really know what garbage values are going to be written into the target array via copying, if any.