【发布时间】:2017-05-24 04:22:52
【问题描述】:
我一直试图在最后释放()内存,但是我的导师说我已经创建了 3 个 malloc 指针(使用当前设置)。
注意:我希望尽可能详细地解释 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
【问题讨论】:
-
Valgrind 是一个很好的工具,可以检查您的程序是否泄漏内存或对内存进行其他不明智的操作。在您的程序中使用 valgrind 可能会发现几个问题。
-
既然有人指出,那我就照办吧:do not cast the return value of malloc.
-
注意:
strcpy(甚至strncpy)的意图可能比memcpy更清晰。 -
至于实际问题:您在循环中运行
malloc,这会发生三次。因此,您拥有三个malloc-ed 内存项。您确实释放了它们,尽管我认为您已经落后了:loopcount > REMAINING将错过第三个午餐项目(索引[2]),其名称是使用 malloc 动态分配的。 -
将指针设置为 null 然后
freeing 显然不正确
标签: c struct memory-leaks malloc dynamic-memory-allocation