Search code examples
cmallocfree

Freeing a pointer to an array within a struct gives AddressSanitizer error


I'm attemping to free an array which has its address stored in a struct, and then free the whole struct itself to make sure its all freed properly. The code looks like this:

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

struct foo {
  uint32_t size;
  uint32_t key[4];
  void* data;
};

struct helper_data {
  uint16_t branching;
  struct info** arr_ptr;
};

int main() {

  struct helper_data* ds = malloc(sizeof(struct helper_data));

  ds->branching = 16;

  struct info* arr = malloc(sizeof(struct foo) * 10);
  ds->arr_ptr = &arr;

  // ... doing work here ...
  // ... doing work here ...
  // ... doing work here ...

  free(ds->arr_ptr);
  free(ds);

  return 0;

}

Note that the freeing of the ds struct actually happens in another function where its being given the pointer to it, but the error is the same either way:

==6880==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x7ffee0148700 in thread T0
    #0 0x10fb152c6 in wrap_free+0xa6 (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x492c6)
    #1 0x10fabae63 in main+0x213 (testing:x86_64+0x100003e63)
    #2 0x7fff204e8620 in start+0x0 (libdyld.dylib:x86_64+0x15620)

Address 0x7ffee0148700 is located in stack of thread T0 at offset 32 in frame
    #0 0x10fabac5f in main+0xf (testing:x86_64+0x100003c5f)

  This frame has 1 object(s):
    [32, 40) 'arr' <== Memory access at offset 32 is inside this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: bad-free (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x492c6) in wrap_free+0xa6
==6880==ABORTING
Abort trap: 6

Is there something wrong with how I'm attemping to free the pointer, how I'm storing it, or something else? I can't quite figure out what would cause this.


Solution

  • The line

    free(ds->arr_ptr);

    is wrong. You must pass an address returned by the function malloc. However, you are instead passing the address of the local variable arr.

    You should write either

    free(arr);

    or

    free(*ds->arr_ptr);

    in order to free the address returned by malloc.