简体   繁体   中英

Allocating memory for one dimensional array in C

I have a question in regards to creating a dynamic array.

int *p; 
p = malloc( 3 * sizeof( int ) );

// initializes elements in the array
for ( int i = 0; i < 3; ++i ) {
    *p++ = i * 4;
}

how can i free the memory i just allocated? for some reason, i find much easier deallocating a two dimensional array than one LOL. It's been along time since the last time i used C.

if i do the following:

free( p ); // will probably get an error. 

Another thing in regards to pointers. I tried this:

int * p = malloc( sizeof( int ) );
*p = 4;

printf( "%d\n", *p ) // prints 4 as expected

free( p );
printf( "%d\n", *p ) // still prints the number 4!!!

the free function should release the block of memory that p points to. how is it that printf stills prints 4 then?

Malloc() returns a pointer to the allocated block. Keep it for future use with free(). Index your array with integer OR walk through it with a pointer, but keep the original address stored somewhere.

You can do like this

int *p = malloc(3 * sizeof(int));
for( int i = 0; i < 3; i++)
   p[i] = 4*i;
// .....
free(p);

or

int *p = malloc(3 * sizeof(int));
int *q = p;
for( int i = 0; i < 3; i++)
   *q++ = 4*i;
// .....
free(p);

In the first case, you just write free(p) as you only allocated one block of memory.

What you are doing in the second case is undefined behaviour. It might print 4, it might crash, it could do literally anything. The chances are that the implementation is just marking that location as reusable, but not actually clearing it out (why should it, it's a waste of time)

free(p) de allocates memory pointed by p . But p still having memory address which is de allocated by free(p) . De-allocation means that block of memory added to list of free memories which is maintained by memory allocation module. When you print data pointed by p still prints value at address because that memory is added to free list and not removed.

  1. how can i free the memory i just allocated?

    You could do something like this

     int *p; p = malloc( 3 * sizeof( int ) ); // initializes elements in the array for ( int i = 0; i < 3; ++i ) { p[i] = i * 4; } 

    this would not change p , so you could use free(p) to free it.

    If you need to change p , you should remember its original value in another variable, and call free() on that original value, such as

     int *op; op = p; /* do something that changes `p` */ free(op); 
  2. how is it that printf stills prints 4

    What you did, access a dynamically allocated memory region after you freed it, will lead to undefined behavior. It could print 4 , it also could crash or do something really wild.

how can i free the memory i just allocated?

When we want to free a memory chunk previously allocated by malloc() , we use the free function. This function accepts a char pointer to a previously allocated memory chunk, and frees it - that is, adds it to the list of free memory chunks, that may be re-allocated. Use free(p) .

how is it that printf stills prints 4 then?

Usage Of free() :

Several notes about free() :

  • The size of the chunk was stored by malloc() previously in its memory map, and that is how free() knows how many bytes to free.
  • The freed memory is not being cleared or erased in any manner. This is why accessing memory that was just freed often does not cause a crash - any data in it is still the same as before calling free() .
  • The free() function cannot nullify pointers to the given memory chunk that might still exist in our program. After we call free() , it is up to us (the programmers) not to try and dereference pointers that still point to that memory chunk . Such pointers are known as 'dangling pointers' - they point to memory that was already freed, and thus they should NOT be dereferenced again, unless they are assigned the address of a different (not-freed) memory chunk.

In first case you can still free the memory by taking the pointer back to the first element's address and then calling free(p) like:

p = p-3;
free(p);

Reason : malloc store some information about how much memory need to be freed once allocated dynamically that's why you need to point it back to the start so that free can read that information and free exactly 3 int memory allocated by malloc.

In your second case it is still printing is not universal result, output can be anything even program may crash.

Reason : free do not do anything special with the memory it only add it back to the FREE LIST it maintains for the memory available for dynamic allocation. It is only up-to the programmer that they do not dereference the after calling free on it.

Malloc ==> Only allocate the memory (not changing memory data to NULL )

Free ==> Only It will release the allocated resources on the pointer,(not changing memory data to NULL )

In both cases user has the responsibly to set appropriate value if required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM