본문 바로가기

C Language

malloc으로 할당해서 쓰는 이유 | The reason for allocating memory by using malloc

메모리를 malloc으로 할당하여 사용하는 이유는 다음과 같습니다:
동적 메모리 할당:
입력 문자열의 길이와 단어 수를 미리 알 수 없습니다.
malloc을 사용하면 실행 시간에 필요한 만큼의 메모리를 할당할 수 있습니다.
메모리 관리:
스택 메모리는 크기가 제한적이며, 대량의 데이터를 저장하기에 부적합할 수 있습니다.
힙 메모리(malloc 사용)는 더 큰 데이터를 저장할 수 있습니다.
함수 반환:
malloc으로 할당된 메모리는 함수가 종료된 후에도 존재합니다.
이를 통해 분할된 문자열을 함수 외부로 반환할 수 있습니다.
메모리 누수 방지:
동적으로 할당된 메모리는 명시적으로 해제할 수 있어, 메모리 관리가 용이합니다.
유연성:
다양한 크기의 입력을 처리할 수 있습니다.
따라서, malloc을 사용하는 것이 이 상황에서 더 적절하고 안전한 방법입니다.

이중포인터의 할당 이유

 

The reasons for using malloc to allocate memory are as follows:
Dynamic Memory Allocation:
The length of the input string and the number of words are not known in advance.
Using malloc allows allocation of memory as needed at runtime.
Memory Management:
Stack memory is limited in size and may be unsuitable for storing large amounts of data.
Heap memory (using malloc) can store larger data.
Function Return:
Memory allocated with malloc persists after the function ends.
This allows returning split strings outside the function.
Preventing Memory Leaks:
Dynamically allocated memory can be explicitly freed, making memory management easier.
Flexibility:
Can handle inputs of various sizes.
Therefore, using malloc is a more appropriate and safer method in this situation.

 

2차원 1차원 포인터 할당 이유