gpt4 book ai didi

c - 对指向指针 "array"的指针的单个 malloc 调用导致无效写入

转载 作者:行者123 更新时间:2023-12-01 13:50:21 24 4
gpt4 key购买 nike

我在这里(出于教育目的)尝试做的是拥有一个指向行为类似于数组但具有单个内存分配的指针的指针。 Valgrind 提示这段代码,如果我用几个分配做这个更长的版本,我在 gdb 中调试时开始出现段错误。

它分配了 144 个字节(24 个字节用于 3 个指针,然后 3*40 个字节用于整数)。 l[0]是l的+24字节,l[1]是l[0]的+40字节,依此类推。

谁能告诉我我哪里出错了?

gcc -o program -g -ansi -Wpedantic -Wall -Wextra main.c

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

int main(void) {
int **l;
int i, j, k;
int x = 3;
int y = 10;
size_t size_y = sizeof(int) * y;
size_t x_ptrs = x * sizeof(int*);
size_t mem_to_alloc = x_ptrs + x * size_y;

l = malloc(mem_to_alloc);

l[0] = (int*)l + x_ptrs;
l[1] = (int*)l + x_ptrs + size_y;
l[2] = (int*)l + x_ptrs + size_y * 2;

k = 0;
for(i = 0; i < x; i++)
for(j = 0; j < y; j++)
l[i][j] = (-k++)*12; /* just some number */

for(i = 0; i < x; i++) {
for(j = 0; j < y; j++) {
printf("%.3d\n", l[i][j]);
}
puts("");
}

free(l);
l = NULL;
return 0;
}

valgrind./程序

==1593== Memcheck, a memory error detector
==1593== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==1593== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==1593== Command: ./program
==1593==
==1593== Invalid write of size 4
==1593== at 0x4006E8: main (main.c:22)
==1593== Address 0x51d5140 is 48 bytes inside an unallocated block of size 4,194,000 in arena "client"
==1593==
000
-012
-024
-036
-048
-060
-072
-084
-096
-108

==1593== Invalid read of size 4
==1593== at 0x400738: main (main.c:26)
==1593== Address 0x51d5140 is 48 bytes inside an unallocated block of size 4,194,000 in arena "client"
==1593==
-120
-132
-144
-156
-168
-180
-192
-204
-216
-228

-240
-252
-264
-276
-288
-300
-312
-324
-336
-348

==1593==
==1593== HEAP SUMMARY:
==1593== in use at exit: 0 bytes in 0 blocks
==1593== total heap usage: 1 allocs, 1 frees, 144 bytes allocated
==1593==
==1593== All heap blocks were freed -- no leaks are possible
==1593==
==1593== For counts of detected and suppressed errors, rerun with: -v
==1593== ERROR SUMMARY: 40 errors from 2 contexts (suppressed: 0 from 0)

最佳答案

当您添加一个整数和一个指针时,该整数会按指针指向的大小进行放大。所以

l[1] = (int*)l + x_ptrs + size_y;

l[1] 设置为 40 * sizeof(int) 字节后 l,即 160 字节过去 l。因为您只分配了 144 字节,所以这超出了数组边界。

这种自动缩放使您可以使用指针算法逐步遍历数组,例如ptr++ 获取 ptr 指向的数组的下一个元素。

关于c - 对指向指针 "array"的指针的单个 malloc 调用导致无效写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32248252/

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