Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MALLOC check ...

Status
Not open for further replies.

ielo

Programmer
Jan 22, 2004
15
0
0
CA
I want to avoid memory allocation/deallocation function problems by first checking (at the start of each function) if a pointer already points to some allocated memory in the heap (before trying to 'malloc' it), or not ...

All the functions that 'free' pointers in turn set the pointer to NULL, so that's an easy check to make for functions that may 'malloc' later on. However, when a pointer type in declared at the begining of the code (imagine a struct with pointers) it isn't set to NULL (so that initial check doesn't work). To get around this, I can only imagine setting them to NULL right after their initial declaration ...

But is there another way of checking for this?
 
If you use calloc, it will initialize array/structure to NULL.

If your structure is declare locally, then

PLIST *ptr = NULL;
 
A function shouldn't care whether its on the heap or not, so long as its valid memory

Code:
void foo ( char *p ) {
}
int main ( ) {
  char array[10];
  char *mem = malloc(10);
  foo( array );
  foo( mem );
}
It's all the same to foo(), and it makes no difference whatsoever to the processing within foo().



--
 
Salem,

Yes, I understand your static vs. dynamically-allocated array-as-a-argument case with the foo subroutine. You're right, it doesn't matter for foo.

That's not my point (excerpts from 'man malloc'):

"Crashes in malloc(), free() or realloc() are almost always related to heap corruption, such as [...] freeing the same pointer twice".

The man pages go on by stating that Linux libc and GNU libc include more functionality (MALLOC_CHECK_) but this doesn't prevent memory leaks and 'unexpected' behaviour.

Up to now, the only security measure I see is what I initially suggested, and what cdlvj seems to support: setting the pointers to 'NULL' when first declared.
 
Alas, freeing twice (or more;) is not the only source of heap corruption. Moreover, it's not a main source. More often we can corrupt heap (stack, code etc;) via "too far" reference.

Yes, it's OK to initialize pointers with 0, but...

Sometimes we can (partially) protect ourselves by using more disciplined "customized" alloc/dealloc package (myalloc()/myfree()) with additional checking.

Don't use paranoic guard of guardian of... approach. Pointers are fast and powerful things. Don't overstate the danger of heap corruption etc. We can't invent silver bullets...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top