Will it cause problems if I call free() on a char* that I never called malloc() for?
Printable View
Will it cause problems if I call free() on a char* that I never called malloc() for?
Probably. And what do you hope to achieve with that?
It was a timing issue I was worried about. There was a chance that the way I had structured my main loop, that I might be freeing a variable that might not have been malloced during the iteration.
I wondered if I'd need to set a flag to make sure.
Another way to check this is to set those variable to NULL when they are declared or freed:
Pointers are never set to NULL (either when initialized or freed) unless you do it, but if they are NULL then you know who did it and why (hopefully: they are already freed or unallocated*). This is easier than using a flag.Code:char *ptr=NULL;
[various things may or may not happen]
if (ptr) { free(ptr); ptr=NULL; }
*remember that setting an allocated pointer to NULL does not free it, so would be a memory leak...
I seem to remember seeing somewhere that you cannot allocate memory for a pointer that is already set to NULL. Is this true?
Instead of NULL, would setting the prt to 0 work?
It is not as obscure as you think: 0 is a null pointer constant.Quote:
Originally Posted by MK27
Personal choice to avoid the use of a macro.Quote:
Originally Posted by MK27
NULL and 0 are essentially the same thing - serves the same purpose and behaves the same. Any particular reason you prefer to use 0?
--
Mats
But then if you have a long function with something like this:
That's why I use NULL. It makes is clear that the variable it's being assigned to is a pointer.Code:char* blah = 0; // You can clearly see it's a pointer since you see the declaration.
...
...
blah = 0; // Not so obvious 50 or more lines down since you can't see how blah is declared. Is it a pointer or an int?
And yes, since NULL is 0 you could assign NULL to an int, but that would just be dumb.
Although, usually the name of the variable itself gives you a pretty good idea about it's type since a lot of people prefix pointers with 'p'...
Hence a function should do one thing and do it well ;)Quote:
Originally Posted by cpjust
Unless a mistake is made for the same reason as you cite NULL being useful. The reader would then be misinformed unless he/she checked, but if he/she checked then the use of NULL would no longer be useful.Quote:
Originally Posted by cpjust
The closest I can say that's remotely connected to is reallocQuote:
Bladactania:
I seem to remember seeing somewhere that you cannot allocate memory for a pointer that is already set to NULL. Is this true