Search code examples
c++pointersdynamic-arrays

C++ change lowercase to Uppercase using a dynamic array


I'm trying to use a Dynamic Array to change a lowercase word into an uppercase word. I ran into something I haven't encountered before called a "Heap Corruption". Can someone explain to me what I am doing wrong and possibly help fix this??

#include <iostream>
#include <cctype>
#include <new>
#include <string>
using namespace std;

int main()
{
    int i;
    int w;
    char *p;
    string str;

    cout << "Change lowercase to UPPERCASE!" << endl;
    cout << "Enter Word: ";
    cin >> str;
    w = str.length();

    p = new (nothrow) char[w];

    if (p == nullptr)
        cout << "Error: memory could not be allocated" << endl;
    else
    {
        cout << "Re-Enter Word: ";
        cin >> p[w];
        for (i = 0; i < w; i++)
            cout << static_cast<char>(toupper(p[i]));
        cout << endl;
    }

    delete[] p;

    cout << "Press <Enter> to Exit";
    cin.get();
    return 0;
}

Solution

  • you made so many mistakes, but to just answer your question:

    p = new (nothrow) char[w + 1];
    

    this is so that we will have room for the null termination character ('\0')

    and also use:

    cin >>  p;