tags:

views:

142

answers:

2

Hi.

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 me error that "Attempting to write to protected memory". How do I free the memory allocated?

Thanks, Rakesh.

+3  A: 

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;
}
paxdiablo
I suppose that cast in `free()` is there because the function takes a non-const `void*`? Because `char*` implicitly converts to `void*`. (And `const char*` to `const void*`.) However, storing the result of allocation as `const T*` doesn't make all too much sense anyway, since you can't change the allocated memory that way. And if it was `char*` (not `const char*`), this code would need one less cast. Of course, all this is moot the moment someone uses `malloc()` and `free()` in C++ anyway...
sbi
+1  A: 

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.

FredOverflow