Podis
Podis

Reputation: 389

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;
}

Upvotes: 0

Views: 2227

Answers (2)

There's no need to use char* for conversion to upper case. Instead you could use std::transform like here:

transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << str << endl;

--- edit ---
If, for whatever (academic) reason, you want to perform the conversion to upper case on a dynamically allocated char array, then you could still use std::transform for that.

However, as you see in the snippet below, you need to allocate one extra character for the trailing \0-char which signals end of string.

char* szStr = new char[w+1];
std::transform(str.begin(), str.end(), szStr, ::toupper);
szStr[w]='\0';
cout << szStr << endl;

Upvotes: 6

radato
radato

Reputation: 930

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;

Upvotes: 1

Related Questions