I'm currently reading the book "C++ primer plus 6th edition" and it says the char pointer needs to be a constant. I don't really understand the explanation so I did some tests.

I don't understand why when I use cin to an already used char pointer, it crashes. But when I assign it, it doesn't crash.

I studied Java so all this memory stuff was hidden from me, so this is a nice challenge.

Post an example program, please.

Thanks for replying, here's an example with comments:

// CharPointerCrash
#include <iostream>

int main () {
    using namespace std;
    char*pChar = "Hello";
    cout << pChar << endl << endl;

    pChar = "Hey"; // it doesn't crash the program

    cout << pChar << endl << endl;

    cin >> pChar; // it crashes the program as soon as I type something and press enter

    return 0;
}

You have a pointer to a string literal. String literals are not modifiable, and very often will be stored in read-only memory, so a crash when you try to write to one is unsurprising.

You can fix the error by owning the memory instead of letting the C++ runtime own it:

char buf[100] = "Hello";
char *pChar = buf;

Or, since the pointer is superfluous in this program, you could just use buf directly and remove pChar.

I see, but why does it only crash when I try to affect a string using cin and not when I affect it directly? Talking about pChar = "Hey";

It's the difference between modifying the pointer (which you own) and modifying the pointed to object (which you don't own).

So if I understand correctly pChar = "Hey"; simply replaces the pointer's address with a new address pointed to the new String object. And the string object that contains "Hey" still exists because it hasn't been deleted. And since C++ doesn't have a garbage collector, it's considered a memory leak.

While cin modifies the object, which it can't access because it's read-only, right?

So if I understand correctly pChar = "Hey"; simply replaces the pointer's address with a new address pointed to the new String object.

Correct.

And since C++ doesn't have a garbage collector, it's considered a memory leak.

It's not a memory leak because you didn't explicitly allocate any memory with, for example, new or malloc(). The memory for string literals is owned and managed by the C++ runtime, and it will release them properly.

While cin modifies the object, which it can't access because it's read-only, right?

Correct.

Thanks! Much better explained than the book!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.