I’m a little bit confused regarding string memory usage in c++.
Is it good reassign *PChar to NULL second time? Will assigned first time to *PChar string memory be released?
char * fnc(int g)
{
...
}
char *PChar = NULL;
PChar=fnc(1);
if (PChar) { sprintf(s,"%s",PChar); } ;
*PChar = NULL;
PChar=fnc(2);
if (PChar) { sprintf(s,"%s",PChar); } ;
First things first. The following statement is not what you intend:
You are NOT assigning null to the pointer, but putting value zero (0) to the first character of the said buffer. You might be willing to do:
As a good programming practice, yes you should assign a pointer to null after it is used (AND possibility memory-deallocated). But assigning a pointer to null will not free the memory – the pointer will not point to allocated memory, but to non-existent memory location. You need to call
deleteif it was allocated usingnew, or need to callfreeif allocated bymalloc.As for the given statement, the compiler would anyway remove the following statement, as the process of optimization:
You need to be very careful while using pointers, and assignment to it with a statically allocated data or dynamically allocated buffer!