char * hello = "helloworld"; //need to use free()?
"helloworld"
is a const char*
and hello
is now a dynamic reference to it. (You will trigger a runtime exception if you try to change any characters in the string, or free
this memory)
char * pointerWmalloc = (char*)malloc(sizeof(char));
This allocated memory needs to be free
'd BEFORE reassignment to
pointerWmalloc = "This need free for sure";
which like hello
now points to a const char
* with the same restrictions.
char * dupOfHello = strdup(hello); //need to use free()?
this needs to be free
'd
char * thisWnew = new Char(); // this need delete for sure
This does need delete
. Also, Char
is not a class unless you make it one, but I think you meant char()
char * charReturnedByFunc = returnchar(); // need to use free() for charReturnedByFunc??
This one is tricky, it completely depends on what returnchar() returns a pointer to. A const char*
? no. A char*
owned by another object or function? Maybe. A char*
allocated inside the function? Maybe. Unless you make it completely clear, you can't know if returnchar()
returns a malloc
'd or new
'd char*
.
All this and more is why it's recommended to avoid raw pointers in favor of std::unique_ptr
and std::shared_ptr
, avoid malloc
in favor of new
, and avoid char*
in favor of std::string
.