释放指向结构中数组的指针会产生 AddressSanitizer 错误

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

我正在尝试释放一个地址存储在结构中的数组,然后释放整个结构本身以确保其全部正确释放。代码如下所示:

#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;

}

请注意 ds 结构的释放实际上发生在另一个函数中,它被赋予指向它的指针,但错误是相同的:

==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

我尝试释放指针的方式、存储指针的方式或其他方式有问题吗?我不太明白是什么原因造成的。

free(ds->arr_ptr);

错了。您必须传递函数 malloc 返回的地址。但是,您传递的是局部变量 arr.

的地址

你应该写任何一个

free(arr);

free(*ds->arr_ptr);

为了释放malloc返回的地址。