Hi,
I know that I can free a block of data in the heap.
BUT can I free the pointer to?
If not is it good practice to set the pointer to 0 ? (ptr = 0)
Thanks.
Hi,
I know that I can free a block of data in the heap.
BUT can I free the pointer to?
If not is it good practice to set the pointer to 0 ? (ptr = 0)
Thanks.
Unless you malloc()'ed the storage for the pointer, don't free() it.
One thing you can do is only use the pointer within the narrowest scope possible, and then when the stack for the block goes away, so does the pointer.
Mainframe assembler programmer by trade. C coder when I can.
Since this is the c board, you should set the pointer to NULL instead of 0. On most platforms NULL == 0, but it's not guaranteed.
Also, freeing a pointer is the same as freeing the block of data you allocated on the heap. When we talk of freeing a pointer, we really mean, freeing the data. And yes, afterwards you should set the pointer to NULL.
QuantumPete
"No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
"Have you tried turning it off and on again?" - The IT Crowd
Thanks
But can I DELETE the pointer? And If I assign it to NULL will the system reuse it (the space that the pointer uses in memory) when he needs it ?
However, 0 is also a null pointer constant.Originally Posted by QuantumPete
Originally Posted by C99, Section 6.3.2.3, Paragraph 3What do you mean?Originally Posted by jordanguyoflove
Once you use free(), the memory may be reused. Setting the pointer to NULL is just so that you can avoid dereferencing a pointer that points to deallocated memory, by checking if that pointer is NULL.Originally Posted by jordanguyoflove
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
You have allocated one space (1 pointer) on the stack for pointer p.Code:int *p; p = malloc(10*sizeof(int));
You have allocated 10 spaces (10 int) on the heap with malloc.
You assign p at the 10 spaces memory on the heap.
Everything on the stack (not using malloc) is freed automatically. You cannot free it yourself.
Everything on the heap is (dynamically allocated) is freed with free().
Now if you had this:
Now you have allocated one pointer on the stack (pointer to pointer to int).Code:int **p; p = malloc(10*sizeof(int));
And 10 pointers on the heap.
You can free the 10 pointers, allocated with malloc(), but not p.
You free ONLY what you malloc(). The rest is done automatically (and faster probably)
Alternatively:
which works in both cases.Code:p = malloc(10 * sizeof(*p));
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
To be honest, laserlight's method is how I typically do it and how I recommend doing it simply because it involves less typing and most importantly, it is always going to be logically sound.
Thanks guys