나는 강사가 (현재 설정으로) 3 개의 malloc'd 포인터를 만들었다 고 말했지만 결국 메모리를 free()하려고 시도했다.구조체와 메모리 할당 루프
참고 : 실제로 메모리에서 진행되고있는 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를 사용하면 몇 가지 문제점이 드러날 수 있습니다. – Evert
다른 사람이 지적하기 때문에 나는 그것을 할 것이다 : [malloc의 반환 값을 캐스트하지 말라] (https://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the- malloc 결과). – Evert
주 :'strcpy' (또는'strncpy')는 의도적으로'memcpy'보다 더 명확 할 수 있습니다. – Evert