gpt4 book ai didi

c - 为两个双指针释放一个 malloc

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:54 25 4
gpt4 key购买 nike

<分区>

在主要方法中我有这个

    int **p1;
int **p2;

//malloc dynamically, let the array 2D [4][3]
p1 = malloc(4 * sizeof(int*));
p2 = malloc(4 * sizeof(int*));

p2[0] = malloc(4 * 3 * sizeof(int));

int i = 0;
for(i = 0; i < 4; i++) {
p1[i]= malloc(3 * sizeof(int));
p2[i + 1] = p2[i] + 3 * sizeof(int);
}

initPtr(array,p1,p2);

int m = 0;
int n = 0;

for (m; m < 4; m++) {
free(p1[m]);
}
free(p2[0]);
free(p1);
}//end of main

当我释放那些内存时出现问题,我收到无效指针 munmap_chunk() 错误。如果有帮助,当我注释掉函数调用时, block [1][2] 和 [3][2] 的 p1 值为 33,其余所有值为 0,包括 p2。我的方法如下

void initPtr(int array[][3], **ptr1, **ptr2) {
//here assign values for the dynamically allocated memory
int i;
int j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
ptr1[i][j] = array[i][j];
ptr2[i][j] = array[i][j];
}
}
}

更新:这是main方法中声明的数组

int array[4][3]={{0,1,2},{3,4,5},{6,7,8},{9,10,11}};

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com