【问题标题】:calloc does not work for large numberscalloc 不适用于大数
【发布时间】:2014-12-22 21:05:34
【问题描述】:

在我的程序中,calloc() 不适用于超过 38 的大小,但如果小于这个数字,它就可以完美运行。在这种情况下,我想分配int中的128个,然后释放它。

怎么了?

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

int main()
{
    int *a;
    int *x;
    x = malloc(512 / sizeof(int));
    a = x;
    int n = (512 / sizeof(int));
    int i;
    for (i = 0; i < n; i++)
    {
        printf("Address of x[%d] = %x\n", i, x );
        printf("Value of x[%d] = %d\n", i, *x );
        x++;
    }
    free(a);
    int *y = (int *)malloc(512 / sizeof(int));
    a = y;
    for (i = 0; i < n; i++)
    {
        printf("Address of y[%d] = %x\n", i, y );
        printf("Value of y[%d] = %d\n", i, *y );
        y++;
        *y = i + 1;
    }
    free(a);
    int *z = (int *)calloc(38, sizeof(int));
    a = z;
    for (i = 0; i < 38; i++)
    {
        printf("Address of z[%d] = %x\n", i, z );
        printf("Value of z[%d] = %d\n", i, *z );
        z++;
    }
    free(a);
    return 0;
}

【问题讨论】:

  • printf("Value of y[%d] = %d\n", i, *y ); *y 未初始化。
  • 如果n = 512 / sizeof(int) 那么malloc(512/sizeof(int)) 是错误的,它必须是malloc(512)
  • 请描述您遇到的错误。还可以考虑从您的示例中删除不相关的代码。我敢打赌,这样做的时候,问题就会消失。
  • calloc doesn't work 没什么好说的了。
  • @user3386109: sizeof(int) 通常为 4(CHAR_BIT 通常为 8),即使在 64 位系统上也是如此。可以有一个 ILP64 系统(其中intlong 和指针是 64 位),但 Unix 上的事实标准是 LP64(long 和指针是 64 位),而它是 LLP64 (long long 和指针是 64 位)适用于 Windows 64 位。

标签: c memory size allocation calloc


【解决方案1】:

第一个问题,您没有初始化 xy 的值,但您仍然尝试打印它们,而另一个更重要的问题是:

n = 512/sizeof(int)

然后你malloc

x = malloc(512/sizeof(int))

你应该这样malloc

x = malloc(n*sizeof(int))

产生

x = malloc(512)

但是既然要分配128 of int,那就更清楚了

n = 128;
x = malloc(n * sizeof(int));

这是固定代码

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

int main()
{
    int *a;
    int *x;
    x = malloc (512);
    a = x;
    int n = (512/sizeof(int));
    int i;
    for (i = 0; i < n; i++)
    {
        *x = i; /* intialize the value of x[i] */
        printf("Address of x[%d] = %p\n", i, x );
        printf("Value of x[%d] = %d\n", i, *x );
        x++;
    }
    free(a);

    int *y = malloc(512);
    a = y;
    for (i = 0; i < n; i++)
    {
        *y = i+1; /* initialize the value of y[i] */
        printf("Address of y[%d] = %p\n", i, y );
        printf("Value of y[%d] = %d\n", i, *y );
        /* *y = i+1; move this before the printf */
        y++;
    }
    free(a);
    int *z = calloc(38, sizeof(int));
    a = z;
    for (i = 0; i < 38; i++)
    {
        printf("Address of z[%d] = %p\n", i, z );
        printf("Value of z[%d] = %d\n", i, *z );
        z++;
    }
    free(a);
    return 0;
}

您必须始终检查malloc 的结果,它在失败时返回NULL。如果它确实返回 NULL 而您不检查,您将取消引用 NULL 指针,这不是一个好主意。

具有讽刺意味的是,您的代码中唯一正确的部分是 calloc 部分,除了不检查其中的返回值。

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 2021-03-22
    相关资源
    最近更新 更多