Search code examples
c++arraysobjectstrncpy

strncpy char string issue when deleting the array


I don't know, problem with this error. However, I think I should delete uName[] before I delete the []cpp. How can I do for this?

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string.h>

using namespace std;
class cppUr
{
public:
    void writeName(char nm[]);
    char * readName();

private:
    char uName[80];
};
void cppUr::writeName(char nm[])
{
    strncpy(uName, nm, 79);
}
char * cppUr::readName()
{
    return uName;
}

The main is:

int main()
{
    char name0[100];
    char name1[100];
    char name2[100];
    char name3[100];
    cppUr *cpp = new cppUr[3];
    cout << "Input first name: "<<endl;
    cin.getline(name0, 100);
    cpp[0].writeName(name0);
    cout << "Input second name: " << endl;
    cin.getline(name1, 100);
    cpp[1].writeName(name1);
    cout << "Input third name: " << endl;
    cin.getline(name2, 100);
    cpp[2].writeName(name2);
    cout << "Input fourth name: " << endl;
    cin.getline(name3, 100);
    cpp[3].writeName(name3);
    for (int i = 0; i < 4; i++)
    {
        cpp[i].readName();
        cout << "The "<<i<<" name " << cpp[i].readName() << endl;
    }
    delete[] cpp;
    system("PAUSE");
    return 0;
}

The error is:

HEAP CORRUPTION DETECTED: after Normal block(#148) at 0x0059E1E0. CRT detected that the application wrote to memory after end of heap buffer


Solution

  • The error is very simple.

    You create array from ccpUr with 3 elements, but after use 4 of them.

    Of course the c++ is null based index language, but that means the last is not useable. That is why in your for cycle condition must be use the same number in like in array allocation which is the 3.

    Think about it, when [3] is enough for 4 element then the [2] is enough for 3 element then [1] is enough for 2 element, and [0] is enough for 1 element? Do you feel it? The zero size array is not enough for nothing.

    regards