bennybp / memwatch

Memory management via preload
1 stars 1 forks source link

Example usage of memwatch? #1

Open robertodr opened 6 years ago

robertodr commented 6 years ago

I am trying to use memwatch but I can't seem to make it work. This is a pretty simple C example I came up with:

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

#include "memwatch.h"

void malloc_report_failure(size_t current_allocation, size_t new_allocation,
                           size_t memory_limit);

int main() {
  memwatch_set_malloc_fail_hook(malloc_report_failure);

  int *int_array;
  int_array = malloc(1024 * sizeof(int));
  double **double_array;
  double_array = malloc(1024 * sizeof(double));
  double_array = (double **)malloc(1024 * sizeof(double *));
  for (int i = 0; i < 1024; i++)
    double_array[i] = (double *)malloc(1024 * sizeof(double));

  free(int_array);
  free(double_array);
}

void malloc_report_failure(size_t current_allocation, size_t new_allocation,
                           size_t memory_limit) {
  printf("Current allocation %zu\n", current_allocation);
  printf("New allocation %zu\n", new_allocation);
  printf("Memory limit %zu\n", memory_limit);
  printf("Bye bye\n");
  abort();
}

I uncommented the printf statements inside the malloc and free functions, but when executing this simple program nothing is printed. Using gdb shows that I never actually hit the "tracking" malloc and free implementations. Am I doing something wrong? This is the CMakeLists.txt I am using (I copy-pasted the header and source file. Very inelegant, I know)

cmake_minimum_required(VERSION 3.7 FATAL_ERROR)

project(example-memwatch LANGUAGES C)

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)

list(APPEND MEMWATCH_C_FLAGS "-std=c99")
list(APPEND MEMWATCH_C_FLAGS "-Wall;-Wextra;-pedantic")
list(APPEND MEMWATCH_C_FLAGS "-Wshadow")

set(CMAKE_BUILD_TYPE "Debug")
add_library(memwatch SHARED memwatch.c)
target_include_directories(memwatch
  PUBLIC
    ${CMAKE_CURRENT_LIST_DIR}
  )
target_compile_options(memwatch PRIVATE ${MEMWATCH_C_FLAGS})
target_link_libraries(memwatch PUBLIC dl)

add_executable(c-example c-example.c)
target_link_libraries(c-example
  PRIVATE
    memwatch
  )
bennybp commented 6 years ago

How are you running the program? You need to preload the SO file in order for it to intercept the calls.

On linux:

LD_PRELOAD=/path/to/libmemwatch.so your_binary

robertodr commented 6 years ago

I was doing just ./c-example. It actually seems to be a problem with my laptop... It's working (with and without the LD_PRELOAD) on another machine.