如何设置动态内存和临时缓冲区?

时间:2012-11-12 21:45:12

标签: c memory dynamic malloc

我一直在尝试完成此代码但我仍然​​坚持创建一个临时缓冲区。我之前从未学过这个,但不知怎的,我需要将它用于我的程序。

来自this website我认为最好的选择是

char * func1() {
     char *buffer = (char *)malloc(1000);
     buffer[0] = '\0'; // Initialize buffer
     // Do processing to fill buffer
     return buffer;
}

以下是我的代码

 #include <stdio.h>
#include <stdlib.h>
#define LUNCHES 5
#define ARRAY 2

int main(void)
{
    int x;
    struct Food
    {
        char *name;                                                            /* “name” attribute of food */
        int weight, calories;                                                  /* “weight” and “calories” attributes of food */
    }lunch[LUNCHES] = { [0] = {"apple", 4, 100}, [1] = {"salad", 2, 80} };

    for(x = ARRAY; x < LUNCHES; ++x)
    {
        char *buff = malloc(sizeof(lunch[x].name));

        printf("Please input \"food\", weight, calories: ");
        scanf("%s", buff);
        scanf("%d %d", &lunch[x].weight, &lunch[x].calories);
        printf("The %s weighs %doz. and contains %d calories.\n", lunch[x].name, lunch[x].weight, lunch[x].calories);


    }

    return 0;
}

好的改变了。但现在输出

NULL称重并包含。为什么空?

校正的

#include <stdio.h>
#include <stdlib.h>
#define LUNCHES 5
#define ARRAY 2

int main(void)
{
    int x;
    struct Food
    {
        char *name;                                                            /* “name” attribute of food */
        int weight, calories;                                                  /* “weight” and “calories” attributes of food */
    }lunch[LUNCHES] = { [0] = {"apple", 4, 100}, [1] = {"salad", 2, 80} };

    for(x = ARRAY; x < LUNCHES; x++)
    {
        lunch[x].name = malloc(25 * sizeof(char));

        printf("Please input \"food\", weight, calories: ");
        scanf("%s", lunch[x].name);
        scanf("%d %d", &lunch[x].weight, &lunch[x].calories);
        printf("The %s weighs %doz. and contains %d calories.\n\n", lunch[x].name, lunch[x].weight, lunch[x].calories);

        free(lunch[x].name);

    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

首先,它是for(x = ARRAY; x < LUNCHES; ++x) - 请注意<而不是<=,否则您将溢出数组(索引从零开始,从0运行到LUNCHES-1)。

至于分配:

  • 您需要为lunch[]数组中的每个条目创建缓冲区,因此在for循环中,您需要类似lunch[x].name = malloc(SIZE)的内容,其中SIZE是一个合理的值 - 用于饭名~80个字符似乎绰绰有余;
  • 接下来必须检查分配给lunch[x].name的指针不是NULL,这会发出内存条件信号 - 否则可能会导致分段解除引用错误;
  • 然后你可以使用指针(到新分配的缓冲区)作为scanf()的参数,但是记得指定最大宽度(即SIZE-1),这样就不会超出未分配的记忆。

当您不再需要数据或程序结束时,请记住在指向已分配内存的指针上使用free() - 而在您的简单示例中,技术上没有必要,它可以轻松启动非常糟糕的习惯。