Ok, let us go on the pointer, previous chapters we get the definition of pointer and how the difference variables allocate in the memory,this chapter i will introduce how to allocate a fixed size of block in the memory(called heap) and then move the pointer in this fixed space.
In "C column of Pointer <0>", we have introduced a function called malloc() to allocate fixed block in the heap , if you don‘t know just refer to that chapter .Here we go, the prototype is
/* size_t is unsigned integer type * you‘d better not define 0 or larger number. * return a void type pointer */ void *malloc(size_t size);
int *sp = malloc(4*sizeof(int)); if(sp == NULL) { //Allocated failure printf("Out of memory"); exit(1); } /*go on the program manipulation*/
My pc is 32bit, and integer type is 32 bits. So this segment of program allocate a 4*4 bytes block in the memory (called heap). The newly allocated block is not initialized. So any data acquired from this block has nothing means, on the contrary, these data maybe confused you if you ignored this issue. So the best way is to initialize them by hand and added this sentence
memset(sp,0,4*sizeof(4));//Initialize zero
When return pointer sp is not null, so allocate successfully, this position is the show by "Arrow 0" ,if you want reload a integer number to this address. Just like using the pointer assignment
*sp = 100;So the first value has been assigned in the allocated block, if you want to set the second , third etc, just move the pointer sp++, then assign the new value to the new address.
sp++; //point to “Arrow 1” *p = 200;// sp++; //point to "Arrow 2" *p = 300;
But here, we make a mistake, if you don‘t need this block and want to free , what should we do?
/*free() release the memory allocated by calloc(), malloc(), realloc() * *@param ptr point to a memory block previously allocted. */ void free(void *ptr);
The answer is no, because we have move the pointer point to another address. So a good manner to allocated a required block is using a temporary pointer to hold the return pointer, then use this pointer to free the block, we don‘t need , the example as below
/* Allocated a requested block then free it */ #include <stdlib.h> int main(void) { int *pf,*sp; pf = malloc(4*sizeof(int)); if( pf == NULL) { printf("Out of memory!\n"); exit(1); } sp = pf; *sp = 100; *sp++ = 200;//As operate precedence *sp++ = *(sp++) *sp++ = 300; sp = pf; printf("The content is %d %d %d\n",*sp,*sp++,*sp++); /*Do not need the 4*4 bytes*/ free(pf); return 0; }
This table really depend on your computer type, especially in embedded device. we must focus on what the size of each type of data be held in memory. Then we can use increment or decrement operator to point to the difference address. But note that , never try to point to the none allocated memory which you don‘t know .
C column of Pointer <2> malloc() free(),布布扣,bubuko.com
C column of Pointer <2> malloc() free()
原文:http://blog.csdn.net/johnnyhan/article/details/24193375