Reputation: 71
I guess I am confused for some reason on how to initialize a char pointer value. Maybe I am overthinking it. I have this in a header file called Login.h char *arg1;
I got a warning that the member variable is not initialized in this constructor. So in Login.cpp I put:
Login::Login() {
// TODO Auto-generated constructor stub
arg1 = (char *)malloc(50);
//arg1 = new char();
//arg1 = nullptr;
}
What is the difference between:
arg1 = (char *)malloc(50);
arg1 = new char(50);
When I try the code below, I get incompatible type.
arg1 = 'A';
I guess I am confused on initializing a pointer vs a normal variable
Should I just do this?
arg1 = nullptr;
Hoping someone can clarify this for me, thanks.
Upvotes: 0
Views: 2203
Reputation: 104589
Presuming arg1
is interpreted to be a character string, this will make the compiler happy in addition to other goodness:
Login::Login() {
// TODO Auto-generated constructor stub
arg1 = (char *)malloc(50);
arg1[0] = '\0';
}
Now arg1
is a properly null terminated string. It's essentially an empty string. Without that = '\0'
initializer, arg1 was a pointer to allocated, but uninitialized memory. Originally, before this change, there's was no guarantee of a null terminator within that allocated 50 byte array. Any attempt to strcpy
the contents of that string, would result in undefined behavior as the copy code could pass the array bounds looking for a null char that isn't there.
Two other things to consider. Why not just declare arg1
to be of type char arg1[50]
or of type std::string arg1
. Then you don't have to worry about freeing the memory as much and your class's default copy constructor will do the right thing.
Upvotes: 1