【问题标题】:malloc allocating the same memory location to 2 pointersmalloc 将相同的内存位置分配给 2 个指针
【发布时间】:2015-06-02 03:40:56
【问题描述】:

在编写c 代码时,我注意到当我更改与指针x 指向的内存位置关联的值时,会导致指针y 指向的数据值发生变化。

当我再次检查时,我发现malloc 正在为 2 个不同的指针分配重叠的内存区域。为什么会这样??

我的代码中有很多动态分配的变量。那么是不是因为malloc可以分配的最大内存量有限制?

以下是我的代码的输出。从输出中可以看到malloc 将重叠的内存区域分配给 x 和 y。

size x:32 y:144 //total size allocated to x and y by malloc

//the memory locations allocated to each of the pointers

location x:0x7fb552c04d20 y:0x7fb552c04c70 

location x:0x7fb552c04d24 y:0x7fb552c04c8c

location x:0x7fb552c04d28 y:0x7fb552c04ca8

location x:0x7fb552c04d2c y:0x7fb552c04cc4

location x:0x7fb552c04d30 y:0x7fb552c04ce0

location x:**0x7fb552c04d34** y:0x7fb552c04cfc

location x:0x7fb552c04d38 y:0x7fb552c04d18

location x:0x7fb552c04d3c y:**0x7fb552c04d34**

我用来分配内存的代码是

int *x = (int *)malloc((DG_SIZE+1)*sizeof(int));
int *y = (int *)malloc(4*(DG_SIZE+2)*sizeof(int));

printf("\n size x:%d y:%d\n", (DG_SIZE+1)*sizeof(int), 4*(DG_SIZE+2)*sizeof(int));

int a = 0;
for(a = 0; a <= DG_SIZE; a++){
   printf("\n location x:%p y:%p\n",(x + a), (y + a*DG_SIZE + 0));
}

【问题讨论】:

  • 发布调用 malloc 的代码
  • int *x = (int *)malloc((DG_SIZE+1)*sizeof(int)); int *y = (int *)malloc(4*(DG_SIZE+2)*sizeof(int));
  • 那么x呢?粘贴通向输出的整个 sn-p。
  • 没有free(),没有循环?
  • @JohnsPaul 另外,不要强制返回 malloc。

标签: c pointers memory-management malloc


【解决方案1】:

y 块在内存中完全位于 x 块之前。没有重叠。

但是,您的循环将地址从y 块的末尾打印到y 列中。

具体来说:

int *y = (int *)malloc(4*(DG_SIZE+2)*sizeof(int));

已分配 36 整数,因为 DG_SIZE7(基于您的输出)。

然后你将a0循环到7并输出(y + a*DG_SIZE + 0)。当a == 6 时,这给出了y + 42,它超出了分配的 36 个整数的末尾。

我猜你的意思是输出y + a*4,而不是y + a*DG_SIZE

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多