为什么我得到双重免费?

问题描述

这是我的代码。尝试malloc被malloc的元素,不知道怎么释放。

char *d = "apple";
int main() {            
  char *a = malloc(10 * sizeof(char));
  char **b = &a;
  strcpy(a,d);
  printf("%c",*b[0]);
  b[0] = malloc(3 * sizeof(char));
  free(b[0]);
  free(a);
}

解决方法

之后

A = [[1,2,3,4,5,6,7,8,9,0],[2,1],[3,1,2],[4,3],[5,4],[6,5]]
A = np.array(A)

height = 3
width = 4
overlap = 1
y_step = height-overlap 
x_step = width-overlap

B = [A[y:y+height,x:x+width] for y in range(0,A.shape[0],y_step) for x in range(0,A.shape[1],x_step)]

/** * Define the behavior of the component here. * Keep on data on the state. */ const onClick = (index: number) => { // Update a field in an object in a list _without mutating_ the objects. setActiveDays([ ...activeDays.slice(0,index),{ ...activeDays[index],active: !activeDays[index].active },...activeDays.slice(index + 1),]); }; // Then {activeDays.map((day: any,i: number) => ( <DaySelector key={day.key} day={day.day} active={day.active} onClick={() => onClick(i)} /> ))} char **b = &a; 相同。所以当你这样做

b[0]

您正在用这个新分配替换 a 的值。

那么 b[0] = malloc(3 * sizeof(char)); a 相同。因此,如果您同时执行这两项操作,那么您将释放相同的内存两次,这是一次双重释放。

您还泄露了分配给 free(b[0]) 的原始分配,因为您不再拥有指向该分配的指针。您需要另一个变量来保存它,以便您可以释放它。

free(a);