I have changed my code, according to the reccommendations to my previous question. Now, i have the following code:
char* id = someFunction();
if (strcmp(id,"0x01") == 0) {
unsigned char cbuffer[]={0x01, 0x00};
id=reinterpret_cast<char*>(cbuffer);
}
My question – is it the correct approach, to pass the {0x01, 0x00} to the id of type char*? And the second question is – how to free the id pointer after?
The code you have posted is dangerous as you are passing a pointer to storage that is in automatic scope. The buffer will be trashed when it leaves scope (the scope of the if in this case).
Instead try something like this:
or even better you could use escape sequences and avoid having to specify the char values yourself:
You can then free the memory used by this string by using
free.