简体   繁体   中英

C/C++ Initialize Char Pointer

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM