-
free()
..
I have 4 huge char segments allocated thru malloc..
the program runs as reqd, in the end when i try to free them, two of them get freed, and then i get a segmeantation fault..
two of them are of size 60,000 bytes, the other 2 are about 1000 bytes..
any ideas as to waht can be going wrong ??
-
Yes, you ran off the end of one of the allocated arrays, trashing vital information used by the memory pool to allow malloc and free to work properly.
-
i think,i have taken enough care that i dont cross the limit...will check anyhow..
besides, the data i am handling is not as big as the space i have allocated..so, i guess there has to be some other reason... and i am not freeinfg freed pointer either..
-
Which OS/Compiler are you using?
-
OS : linux RED HAT
compiler :GCC..
-
As a last resort, you can always pick up dmalloc and link it in with your program. It has good logging that will let you know what's going on.
That is, of course, if a reading of the code doesn't turn up a problem first.
-
In which case do
gcc -g prog.c -lefence
gdb ./a.out
When you run the code in the debugger, you'll hit a breakpoint at the first instruction which oversteps the bounds of it's allocated memory.
One of the more common mistakes is believing
int *p = malloc ( 50 );
allocates space for 50 integers.
Another common mistake is believing
char *p = malloc( strlen(str) );
allocates enough space to make a copy of str.
A third common mistake is believing that realloc() never returns a different pointer to the one you passed to it.
-
that problem is more or less fixed..
just out of curiosity, when we have used "malloc" , what are the other alternatives to free the mem segment allocated..
how exactly does memset work ?? can we use it here ?
-
memset just sets bytes of memory to a specifieed value, it has nothing to do with memory allocation.
If you are using malloc(), the only thing you want to use to free it, is free().
By the way, valgrind is a useful tool under linux for diagnosing memory allocation/leak/heap corruption issues.
-
I habe learnt about the data structure heap, can someone explain how exactly the memory is allocated , when i call malloc().. and does using malloc() increase the build time
-
> can someone explain how exactly the memory is allocated
malloc is an abstraction for the real instruction to the OS to allocate some memory from the heap, so the operating system does all the work. malloc is guaranteed to return NULL or a pointer to at least the amount of space you asked for, so it's nothing for you to worry about how this is done.
The instruction itself may be OS specific, but malloc is standardized: so I think the compiler just writes the correct instruction for malloc depending on the system you compiled the program under.
> and does using malloc() increase the build time
No. All memory is allocated at run time.