문제상황:
C 언어로 개발하던 중 동적할당을 활용한 코드에서 에러가 발생했습니다.
에러가 발생한 코드:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
char name[20];
} Employee;
int main() {
Employee* empList;
int empCount = 5;
empList = (Employee*)malloc(empCount * sizeof(Employee));
for (int i = 0; i <= empCount; i++) {
empList[i].id = i + 1;
snprintf(empList[i].name, sizeof(empList[i].name), "Employee %d", i + 1);
}
for (int i = 0; i <= empCount; i++) {
printf("ID: %d, Name: %s\n", empList[i].id, empList[i].name);
}
free(empList);
return 0;
}
에러로그 내용:
*** Error in `./a.out': malloc(): memory corruption (fast): 0x0000000001a1d030 ***
해결방법:
에러가 수정된 코드+ 수정된 부분에 대한 주석
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
char name[20];
} Employee;
int main() {
Employee* empList;
int empCount = 5;
empList = (Employee*)malloc(empCount * sizeof(Employee));
// 수정: for문에서 i가 empCount와 같을 때까지 반복하는 대신 i < empCount로 변경
for (int i = 0; i < empCount; i++) {
empList[i].id = i + 1;
snprintf(empList[i].name, sizeof(empList[i].name), "Employee %d", i + 1);
}
for (int i = 0; i < empCount; i++) {
printf("ID: %d, Name: %s\n", empList[i].id, empList[i].name);
}
free(empList);
return 0;
}
원인분석:
문제상황에서 사용된 코드는 C 언어로 작성된 간단한 직원 관리 프로그램입니다. 해당 코드는 다음과 같은 작업을 수행합니다:
- Employee라는 구조체를 정의합니다. 이 구조체는 각 직원의 ID(int id)와 이름(char name[20])을 저장합니다.
- main() 함수에서는 먼저 5명의 직원을 저장할 동적할당 메모리 공간을 생성합니다. 이를 위해 empCount 변수에 직원 수를 저장하고, malloc() 함수를 사용하여 직원 수만큼의 공간을 할당합니다.
- 할당된 메모리 공간에 직원 정보를 저장합니다. 각 직원의 ID는 1부터 시작하여 1씩 증가하며, 이름은 "Employee 1", "Employee 2"와 같이 설정합니다. 이 과정에서 snprintf() 함수를 사용하여 문자열을 형식에 맞게 저장합니다.
- 모든 직원의 정보를 출력합니다. printf() 함수를 사용하여 각 직원의 ID와 이름을 출력합니다.
- 마지막으로 사용한 동적할당 메모리를 해제합니다. free() 함수를 사용하여 할당된 메모리를 반납합니다.
문제는 3번 과정에서 발생했습니다. for문의 조건식이 i <= empCount로 되어 있어서, 마지막 반복에서 배열의 범위를 벗어난 메모리에 접근하게 됩니다. 이로 인해 메모리 손상이 발생한 것입니다. 이 문제는 i < empCount로 수정하여 해결할 수 있습니다.
참고링크:
-
[malloc - cppreference.com
Allocates size bytes of uninitialized storage. If allocation succeeds, returns a pointer that is suitably aligned for any object type with fundamental alignment. If size is zero, the behavior of malloc is implementation-defined. For example, a null pointer
en.cppreference.com](https://en.cppreference.com/w/c/memory/malloc)
728x90