Dynamic Memory Deallocation in C -
Dynamic Memory Deallocation in C -
i have these 2 structures , 4 constants:
#define max_blk 16 #define max_str 32 #define c_true 1 #define c_false 0 typedef struct { int rsv; void *addr; int size; char tag[max_str]; } blocktype; typedef struct { int numblocks; blocktype *blocks; } heaptype; here function initializing heap structure:
void mh_init(heaptype *heap) { heap->numblocks = 0; heap->blocks = (blocktype *) malloc(sizeof(blocktype[max_blk])); } here function allocating new block (creates block of n bytes, adds new block , info heap->blocks array, returns pointer of new block of memory):
void *mh_alloc(heaptype *heap, int n, char *label) { void *newaddr = (void*) malloc(n); heap->blocks[heap->numblocks].addr = newaddr; heap->blocks[heap->numblocks].rsv = c_true; heap->blocks[heap->numblocks].size = n; strcpy(heap->blocks[heap->numblocks].tag, label); heap->numblocks += 1; homecoming newaddr; } and in end, free every block , heap structure:
void mh_cleanup(heaptype *heap) { (int = 0; < heap->numblocks; i++) { printf("block %d\n", i); free_block(&heap->blocks[i]); } free(&heap->numblocks); free(heap->blocks); } void free_block(blocktype *block) { free(&(block->rsv)); printf(" freed: rsv,"); if (block->addr != null) { free(block->addr); } printf("adr, "); free(&(block->size)); printf("size, "); free(block->tag); printf("tag\n"); } everything compiles fine when run maintain getting glibc error : "* glibc detected * ./a3: free(): invalid pointer: 0x002b6470 ***"
i've done hr or of research , think error means i'm passing invalid address free(). prints out block 0, frees rsv, nil else. can tell me i'm going wrong approach??
***note there other parts programme don't think important question
this looks suspicious:
free(&(block->rsv)); you should passing pointers free got malloc. in case, you're passing pointer int in construction allocated. if operating on sec construction in array allocated, isn't pointer got malloc. if it's first element, might deallocate whole array if same pointer array (not sure if that's guaranteed), in case rest of function operating on free'd memory, bad.
c memory-management glibc
Comments
Post a Comment