带循环的结构和内存分配

时间:2017-05-24 04:22:52

标签: c struct memory-leaks malloc dynamic-memory-allocation

我一直试图释放()最后的内存但是我的导师说我创建了3个malloc'd指针(使用当前设置)。

注意:我想详细解释有关malloc /内存中实际发生的事情。

我希望能够做些什么来确保没有内存泄漏。

我写了以下内容。

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

    #define LUNCH_ITEMS 5
    #define REMAINING 2
    #define CHAR_SIZE 256

    int main(void)
    {
        struct Food
        {
            char *name; //name attribute of food
            int weight, calories;
        } lunch[LUNCH_ITEMS] = {{"apple", 4, 100}, {"salad", 2, 80},};
        int loopCount;
        //INPUT
        char *namePtr = NULL;
        for (loopCount = REMAINING; loopCount < LUNCH_ITEMS; ++loopCount)
        {
            char tempBuffer[CHAR_SIZE];
            printf("Enter name of item,the weight of item, and the calories in that item: \n");
            // store name string in a tempBuffer. weight and calories directly into lunch structure array address
            scanf("%255s %d %d", tempBuffer, &lunch[loopCount].weight, &lunch[loopCount].calories);
            // get the exact size of (memory of) the input string including add one for null char
            size_t exactMemory = strlen(tempBuffer) + 1;
            //dynamically allocate the exact amount of memory determined in the previous step
            namePtr = (char *)malloc(exactMemory * sizeof(char));
            // check if no memory is allocated for foodPtr
    if (namePtr == NULL)
    {
        fprintf(stderr, "Not enough memory available***\n Terminating Program");
        exit(1);
    }
    //store the pointer to it in the name member of the structure in
    //the current lunch array element.
    (lunch + loopCount)->name = namePtr;
    // Copy the food name (stored in tempbuffer) into the dynamically-allocated
    // memory using the memcpy function

            memcpy(namePtr, tempBuffer, exactMemory);
    //(lunch + loopCount)->name = namePtr;
        }
    //DISPLAY
        printf("Item                        Weight       Cals\n---------------------------------------------\n");
        for (loopCount = 0; loopCount < LUNCH_ITEMS; loopCount++)
        {
            int weight = lunch[loopCount].weight;
            int cals = lunch[loopCount].calories;
            printf("%-12.20s%22d%11d\n", (lunch + loopCount)->name, weight, cals);
            if (loopCount > REMAINING)
            {
                //(lunch+loopCount)->name = NULL;
                namePtr = NULL;
                free(namePtr);
                //free((lunch + loopCount)->name);
            }
        }
        //De-allocate all malloc'd memory
        return EXIT_SUCCESS;
    }

我的输出 -

Item Weight Cals
-----------------
apple  4   100
salad  2    80
hello  22   33
maybe  44   45
right 100   200

2 个答案:

答案 0 :(得分:0)

我认为你的导师关于3个malloc'ed字符串的评论是一个非常强大的线索。我注意到你有一个包含5个项目的数组,预先填充了2个项目。 5 - 2是3。

另外,请注意C中的索引从0开始。预先初始化数组的2个项目将具有索引0和索引1.索引2将是第一个输入的数据。使用&gt;比较该索引2实际上会导致您跳过第一条用户提供的数据的索引。

答案 1 :(得分:0)

查看初始化循环:

for (loopCount = REMAINING; loopCount < LUNCH_ITEMS; ++loopCount)
{
    // The code inside the loop will be executed for
    // loopCount being equal to 
    //     REMAINING
    //     REMAINING + 1
    //     ....
    //     LUNCH_ITEMS - 1
    //
    // So in your case, you execute this code for
    // loopCount equal to 2, 3 and 4
}

换句话说,循环中的代码执行3次,即,你将malloc调用3次

以同样的方式,查看释放内存的循环。

for (loopCount = 0; loopCount < LUNCH_ITEMS; loopCount++)
{
    // you execute this code for
    // loopCount equal to 0, 1, 2, 3 and 4

    // ....

    if (loopCount > REMAINING)
    {
        // Since REMAINING is 2, you execute this code for
        // loopCount equal 3 and 4
    }
}

因此if正文中的代码仅执行 2 次。你真的想要 3 次(即loopCount等于2,3和4)。因此,您需要将代码更改为:

    if (loopCount >= REMAINING)  // Notice the = sign
    {
        // Since REMAINING is 2, you execute this code for
        // loopCount equal 2, 3 and 4
    }

现在关于mallocfree。释放内存时,即使用free,您必须准确传递malloc返回给您的值

在初始化中,您保存了指针,如下所示:

namePtr = (char *)malloc(exactMemory * sizeof(char));
// ...
(lunch + loopCount)->name = namePtr;  // Save pointer

所有(lunch + loopCount)->name将用于free。像:

    if (loopCount >= REMAINING)  // Notice the = sign
    {
        free((lunch + loopCount)->name);

        // Optional part but always after calling free
        (lunch + loopCount)->name = NULL;
    }

BTW:注意

(lunch + loopCount)->name

相同
lunch[loopCount].name

许多人认为更容易阅读。