Freeing memory for const char * variable in C++
I have a variable declared as const char *. I have allocated memory for that using malloc(). After using it, I want to free that memory using free(). But I am not able to do that and it gives m开发者_JAVA技巧e error that "Attempting to write to protected memory". How do I free the memory allocated?
Thanks, Rakesh.
If you're getting that error then you're doing something wrong and you'll need to post the code so we can figure out what it is. For what it's worth, you can free a const char*
as evidenced in the following code, which compiles and executes perfectly:
#include <cstdlib>
int main (void) {
const char *x = (const char*) malloc (100);
free ((void*) x);
return 0;
}
After using it
Let me guess, is this what you did?
const char* p = malloc(12);
p = "hello world"; // problem: memory leak
free(p); // problem: trying to free static memory
You should replace the second line with strcpy(p, "hello world");
or something similar to get rid of the problem. But since you did not provide any code, I'm not going to delve any further into this matter.
精彩评论