【问题标题】:How can I free memory in a dynamically allocated array? [duplicate]如何释放动态分配的数组中的内存? [复制]
【发布时间】:2017-02-02 11:59:23
【问题描述】:

我是一个新手,试图学习如何在 C 中创建动态数组。当我使用 code:blocks 构建它时,该代码不会给我任何错误,但是当我运行它时它会崩溃。我认为崩溃与我释放内存的方式有关,因为代码在崩溃之前给了我想要的输出。

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

int main()
{

    int i, j;
    int *p = (int *)malloc(sizeof(*p));

    printf("Hello World! I have created a dynamic array of 20x30 integers! \n");
    for (i = 0; i <= 19; i++)
    {
        p[i] = (int )malloc(sizeof(int*));
        printf(" %2d ", i);
        for (j = i + 1; j <= 29 + i; j++)
        {
        p[i] = 0;
        printf("%2d", j);
        }
    printf("\n");
    }

    for (i = 0; i <= 19; i++);
    {
        free(p[i]);
    }
    free(p);
    return 0;
}

【问题讨论】:

  • 您的第一个 malloc 为单个 int 分配空间。
  • 另外,p[i] = (int )malloc(sizeof(int*)); 是错误的。 p[i]int 而不是指针,因此您不应在其中存储指针。在许多系统上,int 的大小和指针是不同的,因此该代码也可能导致崩溃。
  • 不需要在C中强制转换malloc和friends的结果,也不推荐任何方式。更重要的是,它可能会像您的情况一样隐藏错误。删除所有那些无用的强制转换,重新编译,修复代码,直到不再发出警告,开心。 :-) 您还想更改此malloc(sizeof(*p)); 以分配足够的指针,而不仅仅是一个。

标签: c


【解决方案1】:

这就是问题所在。

首先,您的第一个 malloc 调用为单元素数组分配空间。

你会想要改变它

int *p = (int *)malloc(sizeof(*p));

int *p = (int *)malloc(sizeof(int*) * 20);

然后你的第二个 malloc 调用也有点不正确。

p[i] = (int )malloc(sizeof(int*));

应该改为

p[i] = (int *)malloc(sizeof(int));

你只是把星号放错地方了。

最后,你真的只创建了一个 20 元素的数组。你在内部 for 循环中所做的就是为数组中的每个单元分配 0 次值。如果你想创建一个 20x30 数组,你总是可以采取简单的方法,创建一个 1D 数组并使用一些数学运算(这最终是编译器对非动态 2D 数组所做的):

int main()
{
    int *p = (int *)malloc(sizeof(int) * 600);
    ...
    for (i = 0; i <= 19; i++)
    {
        printf(" %2d ", i);
        for (j = 0; j <= 29; j++)
        {
            p[i * 30 + j] = 0; // It's i * 30, not i * 20 because you have to skip the space that the 'j' dimension takes up.
            printf("%2d", j);
        }
        printf("\n");
    }

    free((void*)p); //I found the program crashes without the void* cast
}

我已经测试了这段代码并且它运行了。

希望这会有所帮助。

【讨论】:

  • 使用int * p; p[i] 计算结果为int。您不想将指针(malloc() 的结果是什么)存储到 int 中。
  • 这个p[i][j] 甚至不会编译。
  • alk,我写的很匆忙,知道它可能有错误。我现在已经修复了它,并提供了更好的解决方案。
  • :-) 但是,所有这些演员都是无用的。这是 C 而不是 C++。在 C 中,不需要也不推荐使用 malloc 和朋友。
  • 谨此奉劝:不要着急回答。
猜你喜欢
  • 2013-01-27
  • 2011-03-17
  • 2017-06-13
  • 1970-01-01
  • 2016-07-16
  • 2018-09-06
  • 2013-04-14
  • 2013-11-22
相关资源
最近更新 更多