이것은 C에서 메모리를 다루는 기본적인 부분입니다. 전구를 윙크하기 전에 친구가되어야하는 것은 어렵지 않습니다. 당신은 동적 메모리, malloc
, calloc
및 realloc
를 할당하는 세 가지 도구가
을 (참고 컴파일러는 C99 가변 길이 배열 객체를 지원 경우, 당신은 여기에 언급되지 않은, 동적으로 할당하는 대신 VLA를 사용할 수 있습니다) .(calloc
는 malloc
과 같은 일을하지만 제로로 모든 바이트를 초기화 - 유용한 모든 메모리가 초기화되고 약간 느린 malloc
보다 보험에 가입 할 경우) 귀하의 예를 들어
, 당신이 당신의 개체를 동적으로 메모리를 할당 할 수있다 (주에게 아래의 /* comments */
에서 추가 정보)를 다음과 같이
#include <stdio.h>
#include <stdlib.h>
typedef struct { /* a typedef will do (and make things easier) */
int xcdnt; /* C generally uses all lowercase variable and */
int ycdnt; /* function names, avoiding MixedCase or */
int zcdnt; /* camelCase, reserving all uppercase for */
int mass; /* constants and macros. */
} object;
int main (void) {
int objectcount = 0;
int dimensioncount = 0;
object *objects = NULL;
printf ("How many objects are there?: ");
if (scanf (" %d", &objectcount) != 1) { /* validate ALL user input */
fprintf (stderr, "error: invalid conversion or EOF.\n");
return 1;
}
printf ("How many dimensions are used?: ");
if (scanf (" %d", &dimensioncount) != 1) {
fprintf (stderr, "error: invalid conversion or EOF.\n");
return 1;
}
/* create objectcount objects using calloc */
objects = calloc (objectcount, sizeof *objects);
if (!objects) { /* validate all memory allocations */
fprintf (stderr, "error: virtual memory exhausted.\n");
return 1;
}
/* create some random values */
for (int i = 0; i < objectcount; i++) {
objects[i].xcdnt = i;
objects[i].ycdnt = i + 1;
objects[i].zcdnt = i + 2;
objects[i].mass = i % 10 + 5;
}
printf ("\ndimensioncount: %d\n\n", dimensioncount);
/* output the random data in objects */
for (int i = 0; i < objectcount; i++) {
printf ("X coordinate is %d.\nY coordinate is %d.\n"
"Z coordinate is %d.\nmass is: %d\n\n",
objects[i].xcdnt, objects[i].ycdnt, objects[i].zcdnt,
objects[i].mass);
}
free (objects); /* don't forget to free the memory you allocate */
return 0;
}
사용 예/출력을
$ /bin/dynamicobjects
How many objects are there?: 10
How many dimensions are used?: 3
dimensioncount: 3
X coordinate is 0.
Y coordinate is 1.
Z coordinate is 2.
mass is: 5
X coordinate is 1.
Y coordinate is 2.
Z coordinate is 3.
mass is: 6
<snip... objects[2-7]>
X coordinate is 8.
Y coordinate is 9.
Z coordinate is 10.
mass is: 13
X coordinate is 9.
Y coordinate is 10.
Z coordinate is 11.
mass is: 14
메모리 사용/오류 동적으로 메모리를 할당하는 쓰기 코드에서 확인
, 당신은 할당 된 메모리의 블록에 대한 2 개 책임있다 : (1) 항상 시작 주소에 대한 포인터를 유지를 메모리 블록에 대해, (2) 더 이상 필요하지 않을 때 이 해제되어이 될 수 있습니다.
메모리 오류 검사 프로그램을 사용하면 할당 된 메모리 블록의 경계를 넘어 서기를 시도하거나 초기화되지 않은 값에 조건부 점프를 읽거나 시도하지 않도록 할 수 있습니다. , 할당 한 모든 메모리를 확보했는지 확인하십시오.
Linux의 경우 valgrind
이 정상 선택입니다. 모든 플랫폼에 대해 유사한 메모리 검사기가 있습니다. 그들은 모두 사용하기 쉽고, 프로그램을 실행하면됩니다.
$ valgrind ./bin/dynamicobjects
==9105== Memcheck, a memory error detector
==9105== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==9105== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==9105== Command: ./bin/dynamicobjects
==9105==
How many objects are there?: 10
How many dimensions are used?: 3
dimensioncount: 3
X coordinate is 0.
Y coordinate is 1.
Z coordinate is 2.
mass is: 5
<snip... remaining>
==9105==
==9105== HEAP SUMMARY:
==9105== in use at exit: 0 bytes in 0 blocks
==9105== total heap usage: 1 allocs, 1 frees, 160 bytes allocated
==9105==
==9105== All heap blocks were freed -- no leaks are possible
==9105==
==9105== For counts of detected and suppressed errors, rerun with: -v
==9105== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
할당 한 메모리를 모두 비우고 메모리 오류가 없는지 항상 확인하십시오.
궁금한 점이 있으면 자세히 살펴보고 알려주세요.