Friday, December 2, 2011

MALLOC Failure Test Program in C

Wanna test malloc failure without changing the binary of the application. [Works good for C]

Try the below program. 

#############
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <unistd.h>

static int mCnt;
typedef void* (*MallocFn)(size_t size);

MallocFn mMalloc;
extern "C" {
  void* malloc(size_t size)
  {
    mCnt++;
    if (!mMalloc){
        mMalloc = (MallocFn)dlsym(RTLD_NEXT, "malloc");
    }
    if(mCnt >=20){
      printf("MyMalloc is called\n");
      return NULL;
    }
    else{
      return mMalloc(size);
    }
  }
}
 
#############
compilation : gcc -shared -ldl -fPIC mallocTest.c -o libMyMalloc.so
before running your application, export the LD_PRELOAD evn.
export LD_PRELOAD=<absolute path of the libMyMalloc.so file>
run the binary or application. 

    if(mCnt >=20){

Above line controls the malloc behaviour, when application uses 20th malloc onwards, memory will not be allocated.


Regards 
-Praveen
Pin It
Related Posts Plugin for WordPress, Blogger...