1

After watching section on "Dynamically allocated memory" (from Week 4) several times, I still have a question unanswered. Consider the following code-

// Allocates 4 bytes of memory on heap and returns its address to pointer "px" which is created on stack
//(the pointer "px" occupying memory on stack
//which can vary from 4 to 8 bytes depending on compiler, as said during one of the lectures)

int* px = malloc(sizeof(int);

// assigns value "3" to the block of memory at which "px" is pointing.

*px = 3;

// frees up the block of memory to which px was pointing.

free();

And now if we try-

*px = 4;

We gets, as expected a seg fault. That confirms that the memory block allocated on heap has been freed, BUT what happens to the memory which our pointer "px" was occupying on stack?

4

Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address. It will not automatically be changed to NULL or anything else.

The only thing that will remove the pointer var from the stack would be if it went out of scope, just like any other variable. This happens when the code goes outside the curly brace pair where the var is declared. Given the memory capacity of computers today, unless you're creating massive numbers of variables, it's not a problem.

To see this demonstrated, run the code below. If you want to also see the effect of scope, add another pair of curly braces around the code and try to print the address in the pointer before the last closing brace.

#include <cs50.h>
#include <stdio.h>

int main(void)
{
  {
    int* px = malloc(sizeof(int));
    *px = 3;
    printf("&px = %i, px = %p\n", *px, px);


    free(px);

    if( px == NULL)
        printf("px is null after free\n");
    else
        printf(" px = %p\n",px);
   }
//     this printf would demonstrate that px is out of scope.
//            printf(" px = %p\n",px);
}

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Thank you so much. exactly the information i want to know. just one last thing. After the pointer variable goes out of scope, does the memory block containing that pointer variable gets free automatically by default, as if nothing (that pointer variable to be precise) was ever kept there even if the program is still running?
    – Vinz.R
    Aug 8 '16 at 8:48
  • Stack and heap usage will be covered in more depth in the course. I'll leave it to Prof. Malan to explain. ;-)
    – Cliff B
    Aug 8 '16 at 9:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .