c - Avoiding Memory Allocation related errors -
i have complex c code me , while executing it, chanced upon following errors:
- glibc: corrupted double-linked list
- glibc: malloc() memory corruption
- munmap_chunk() invalid pointer
i realized 1) associated freeing freed memory. still trying figure out reasons 2) , 3).
well, thing did searches , got general opinion must debug "valgrind" detect memory corruption related problems.
ok, coming point,when searched forum, have dug code posted at: what best way free memory after returning error?
and piece of code had solved problems:
int func(void **mem1, void **mem2) { *mem1 = null; *mem2 = null; *mem1 = malloc(size); if(!*mem1) goto err; *mem2 = malloc(size); if(!*mem2) goto err; return 0; err: if(*mem1) free(*mem1); if(*mem2) free(*mem2); *mem1 = *mem2 = null; return 1; }
well solved issue line:
eg:
char *ptr = null; ptr = (char *)malloc(size); assign , use ptr free(ptr);
how char *ptr = null helping???? infact when assigned null in beginning, didn't use free(ptr). still worked liked charm(i tried executing several times)
when remove null assignment in beginning error 1) :( :(
i going install valgrind before insights on this.
thanks
i'll take shot in dark , guess attempt free()
ptr
pointer before allocating malloc()
.
if has been initialized null
, free()
implementations nothing. free()
manual page:
free() frees memory space pointed ptr, must have been returned previous call malloc(), calloc() or realloc(). otherwise, or if free(ptr) has been called before, undefined behaviour occurs. if ptr null, no operation performed.
if has not been set null, trying free either random pointer, or has been been freed.
that said, valgrind is best tool detect such errors on posix systems.
edit:
what needs understood c not java , not have luxuries of vm. exists within same address space, minimal protections - , includes structures of memory allocator. once memory-related error occurs, there no way predict how make known.
of other 2 errors, i'd guess @ first glance (3) once again related freeing address has not been allocated. there no way, however, sure issue. once memory of process corrupted, cannot trust anything tells - what's happening in case.
just use proper debugging tools gdb or valgrind , save (and us) pain of guessing blindly...
Comments
Post a Comment