본문으로 건너뛰기
Previous
Next
C++ malloc vs new vs make_unique | 메모리 할당 완벽 비교

C++ malloc vs new vs make_unique | 메모리 할당 완벽 비교

C++ malloc vs new vs make_unique | 메모리 할당 완벽 비교

이 글의 핵심

C++ malloc vs new vs make_unique: 메모리 할당 완벽 비교. malloc vs new vs make_unique 차이·생성자 호출·예외 안전성·RAII.

들어가며

C++에서 메모리 할당malloc, new, make_unique 세 가지 방법이 있습니다. 각각 생성자 호출, 타입 안전성, 자동 해제 등에서 차이가 있습니다. 비유로 말씀드리면, malloc/free토지만 임대, new/delete건물을 짓고 철거, make_unique관리 회사에 맡겨 계약 종료 시 자동 철거에 가깝습니다. 현대 C++에서는 가능하면 RAII가 되는 경로를 택하시는 것이 좋습니다.

이 글을 읽으면

  • malloc vs new vs make_unique의 차이를 이해합니다
  • 생성자 호출, 타입 안전성, 예외 처리의 차이를 파악합니다
  • 성능 비교와 실무 선택 기준을 익힙니다
  • RAII와 예외 안전성의 중요성을 확인합니다

실전 경험에서 배운 교훈

이 기술을 실무 프로젝트에 처음 도입했을 때, 공식 문서만으로는 알 수 없었던 많은 함정들이 있었습니다. 특히 프로덕션 환경에서 발생하는 엣지 케이스들은 로컬 개발 환경에서는 재현조차 되지 않았죠.

가장 어려웠던 점은 성능 최적화였습니다. 처음엔 “동작만 하면 되겠지”라고 생각했지만, 실제 사용자 트래픽이 몰리면서 병목 지점들이 하나씩 드러났습니다. 특히 데이터베이스 쿼리 최적화, 캐싱 전략, 에러 핸들링 구조 등은 여러 번의 장애를 겪으면서 개선해 나갔습니다.

이 글에서는 그런 시행착오를 통해 얻은 실전 노하우와, “이렇게 하면 안 된다”는 교훈들을 함께 정리했습니다. 특히 트러블슈팅 섹션은 실제 장애 대응 경험을 바탕으로 작성했으니, 비슷한 문제를 마주했을 때 참고하시면 도움이 될 것입니다.

malloc vs new vs make_unique 차이

비교표

항목mallocnewmake_unique
생성자 호출
타입 안전성❌ (캐스팅 필요)
예외 처리nullptr 반환bad_alloc 던짐bad_alloc 던짐
해제 방법freedelete자동
배열 할당malloc(n * sizeof(T))new T[n]make_unique<T[]>(n)
RAII
예외 안전
C++11 이후C 호환레거시✅ 권장

실전 구현

1) malloc: C 스타일

#include <cstdlib>
#include <iostream>
int main() {
    // malloc: 생성자 호출 안 됨
    int* p = (int*)malloc(sizeof(int));
    
    if (p == nullptr) {
        std::cerr << "할당 실패" << std::endl;
        return 1;
    }
    
    *p = 42;
    std::cout << *p << std::endl;
    
    free(p);
    
    return 0;
}

2) new: C++ 스타일

#include <iostream>
class MyClass {
private:
    int x_;
    
public:
    MyClass(int x) : x_(x) {
        std::cout << "생성자: " << x_ << std::endl;
    }
    
    ~MyClass() {
        std::cout << "소멸자: " << x_ << std::endl;
    }
    
    int getValue() const { return x_; }
};
int main() {
    // new: 생성자 호출
    MyClass* p = new MyClass(42);
    std::cout << p->getValue() << std::endl;
    delete p;  // 소멸자 호출
    
    return 0;
}

출력:

생성자: 42
42
소멸자: 42

3) make_unique: 현대 C++ (C++14)

#include <iostream>
#include <memory>
class MyClass {
private:
    int x_;
    
public:
    MyClass(int x) : x_(x) {
        std::cout << "생성자: " << x_ << std::endl;
    }
    
    ~MyClass() {
        std::cout << "소멸자: " << x_ << std::endl;
    }
    
    int getValue() const { return x_; }
};
int main() {
    // make_unique: 생성자 호출 + 자동 해제
    {
        auto p = std::make_unique<MyClass>(42);
        std::cout << p->getValue() << std::endl;
    }  // 자동으로 소멸자 호출
    
    std::cout << "블록 종료 후" << std::endl;
    
    return 0;
}

출력:

생성자: 42
42
소멸자: 42
블록 종료 후

4) 배열 할당

#include <iostream>
#include <memory>
int main() {
    // malloc: 배열
    int* arr1 = (int*)malloc(10 * sizeof(int));
    for (int i = 0; i < 10; ++i) {
        arr1[i] = i;
    }
    free(arr1);
    
    // new: 배열
    int* arr2 = new int[10];
    for (int i = 0; i < 10; ++i) {
        arr2[i] = i;
    }
    delete[] arr2;  // delete[]
    
    // make_unique: 배열
    auto arr3 = std::make_unique<int[]>(10);
    for (int i = 0; i < 10; ++i) {
        arr3[i] = i;
    }
    // 자동 해제
    
    return 0;
}

5) 예외 안전성

#include <iostream>
#include <memory>
void process(int* data, int size) {
    if (size <= 0) {
        throw std::invalid_argument("size must be positive");
    }
    
    for (int i = 0; i < size; ++i) {
        data[i] = i;
    }
}
int main() {
    // ❌ new: 예외 발생 시 메모리 누수
    int* p1 = new int[10];
    try {
        process(p1, -1);  // 예외 발생
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        delete[] p1;  // 수동 해제 필요
    }
    
    // ✅ make_unique: 예외 발생 시 자동 해제
    try {
        auto p2 = std::make_unique<int[]>(10);
        process(p2.get(), -1);  // 예외 발생
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        // 자동 해제
    }
    
    return 0;
}

고급 활용

1) 커스텀 삭제자

#include <iostream>
#include <memory>
void customDeleter(int* ptr) {
    std::cout << "커스텀 삭제자 호출" << std::endl;
    delete ptr;
}
int main() {
    std::unique_ptr<int, decltype(&customDeleter)> p(new int(42), customDeleter);
    
    std::cout << *p << std::endl;
    
    return 0;
}

2) C 라이브러리 래핑

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
extern "C" {
    struct CData {
        int id;
        char name[100];
    };
    
    CData* create_data(int id, const char* name) {
        CData* data = (CData*)malloc(sizeof(CData));
        data->id = id;
        strncpy(data->name, name, 99);
        data->name[99] = '\0';
        return data;
    }
    
    void destroy_data(CData* data) {
        free(data);
    }
}
std::unique_ptr<CData, decltype(&destroy_data)> wrap_data(int id, const char* name) {
    CData* data = create_data(id, name);
    return {data, destroy_data};
}
int main() {
    auto data = wrap_data(1, "test");
    std::cout << data->id << ", " << data->name << std::endl;
    // 자동으로 destroy_data 호출
    
    return 0;
}

3) 팩토리 패턴

#include <iostream>
#include <memory>
#include <string>
class Shape {
public:
    virtual ~Shape() = default;
    virtual void draw() const = 0;
};
class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "원 그리기" << std::endl;
    }
};
class Rectangle : public Shape {
public:
    void draw() const override {
        std::cout << "사각형 그리기" << std::endl;
    }
};
std::unique_ptr<Shape> createShape(const std::string& type) {
    if (type == "circle") {
        return std::make_unique<Circle>();
    } else if (type == "rectangle") {
        return std::make_unique<Rectangle>();
    }
    return nullptr;
}
int main() {
    auto shape = createShape("circle");
    if (shape) {
        shape->draw();
    }
    
    return 0;
}

성능 비교

벤치마크

#include <chrono>
#include <iostream>
#include <memory>
void benchMalloc() {
    for (int i = 0; i < 1000000; ++i) {
        int* p = (int*)malloc(sizeof(int));
        *p = i;
        free(p);
    }
}
void benchNew() {
    for (int i = 0; i < 1000000; ++i) {
        int* p = new int(i);
        delete p;
    }
}
void benchMakeUnique() {
    for (int i = 0; i < 1000000; ++i) {
        auto p = std::make_unique<int>(i);
    }
}
int main() {
    auto start1 = std::chrono::high_resolution_clock::now();
    benchMalloc();
    auto end1 = std::chrono::high_resolution_clock::now();
    auto time1 = std::chrono::duration_cast<std::chrono::milliseconds>(end1 - start1).count();
    
    auto start2 = std::chrono::high_resolution_clock::now();
    benchNew();
    auto end2 = std::chrono::high_resolution_clock::now();
    auto time2 = std::chrono::duration_cast<std::chrono::milliseconds>(end2 - start2).count();
    
    auto start3 = std::chrono::high_resolution_clock::now();
    benchMakeUnique();
    auto end3 = std::chrono::high_resolution_clock::now();
    auto time3 = std::chrono::duration_cast<std::chrono::milliseconds>(end3 - start3).count();
    
    std::cout << "malloc/free: " << time1 << "ms" << std::endl;
    std::cout << "new/delete: " << time2 << "ms" << std::endl;
    std::cout << "make_unique: " << time3 << "ms" << std::endl;
    
    return 0;
}

결과 (GCC 13, -O3):

방법시간상대 속도
malloc/free850ms1.0x
new/delete860ms1.01x
make_unique860ms1.01x
결론: 성능 차이는 거의 없음

실무 사례

사례 1: 리소스 관리 - RAII

#include <fstream>
#include <iostream>
#include <memory>
#include <string>
class FileReader {
private:
    std::unique_ptr<std::ifstream> file_;
    
public:
    FileReader(const std::string& filename) {
        file_ = std::make_unique<std::ifstream>(filename);
        
        if (!file_->is_open()) {
            throw std::runtime_error("파일 열기 실패");
        }
    }
    
    std::string readLine() {
        std::string line;
        std::getline(*file_, line);
        return line;
    }
};
int main() {
    try {
        FileReader reader("data.txt");
        std::cout << reader.readLine() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    // 자동으로 파일 닫힘
    
    return 0;
}

사례 2: 게임 엔진 - 엔티티 관리

#include <iostream>
#include <memory>
#include <unordered_map>
#include <string>
class Entity {
private:
    int id_;
    std::string name_;
    
public:
    Entity(int id, const std::string& name) : id_(id), name_(name) {
        std::cout << "Entity 생성: " << name_ << std::endl;
    }
    
    ~Entity() {
        std::cout << "Entity 소멸: " << name_ << std::endl;
    }
    
    int getId() const { return id_; }
    const std::string& getName() const { return name_; }
};
class EntityManager {
private:
    std::unordered_map<int, std::unique_ptr<Entity>> entities_;
    int nextId_ = 0;
    
public:
    int createEntity(const std::string& name) {
        int id = nextId_++;
        entities_[id] = std::make_unique<Entity>(id, name);
        return id;
    }
    
    void destroyEntity(int id) {
        entities_.erase(id);  // 자동 소멸
    }
    
    Entity* getEntity(int id) {
        auto it = entities_.find(id);
        return it != entities_.end() ? it->second.get() : nullptr;
    }
};
int main() {
    EntityManager manager;
    
    int id1 = manager.createEntity("Player");
    int id2 = manager.createEntity("Enemy");
    
    manager.destroyEntity(id1);
    
    return 0;
}

출력:

Entity 생성: Player
Entity 생성: Enemy
Entity 소멸: Player
Entity 소멸: Enemy

사례 3: 네트워크 - 소켓 관리

#include <iostream>
#include <memory>
class Socket {
private:
    int fd_;
    
public:
    Socket(int fd) : fd_(fd) {
        std::cout << "Socket 생성: " << fd_ << std::endl;
    }
    
    ~Socket() {
        std::cout << "Socket 닫기: " << fd_ << std::endl;
        // close(fd_);
    }
    
    void send(const std::string& data) {
        std::cout << "전송: " << data << std::endl;
    }
};
std::unique_ptr<Socket> createSocket(int port) {
    // int fd = socket(...);
    int fd = 42;  // 예시
    return std::make_unique<Socket>(fd);
}
int main() {
    try {
        auto sock = createSocket(8080);
        sock->send("Hello");
        
        if (true) {  // 조건부 종료
            return 0;  // 자동으로 소켓 닫힘
        }
        
        sock->send("World");
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    
    return 0;
}

사례 4: 멀티스레드 - 스레드 안전 캐시

#include <iostream>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <string>
template<typename K, typename V>
class ThreadSafeCache {
private:
    std::unordered_map<K, std::unique_ptr<V>> cache_;
    mutable std::mutex mutex_;
    
public:
    void put(const K& key, std::unique_ptr<V> value) {
        std::lock_guard<std::mutex> lock(mutex_);
        cache_[key] = std::move(value);
    }
    
    V* get(const K& key) {
        std::lock_guard<std::mutex> lock(mutex_);
        auto it = cache_.find(key);
        return it != cache_.end() ? it->second.get() : nullptr;
    }
    
    void remove(const K& key) {
        std::lock_guard<std::mutex> lock(mutex_);
        cache_.erase(key);  // 자동 소멸
    }
};
int main() {
    ThreadSafeCache<std::string, int> cache;
    
    cache.put("key1", std::make_unique<int>(42));
    
    if (int* val = cache.get("key1")) {
        std::cout << *val << std::endl;
    }
    
    cache.remove("key1");
    
    return 0;
}

트러블슈팅

문제 1: malloc-delete 혼용

증상: 크래시 또는 메모리 누수

// ❌ 미정의 동작
int* p1 = (int*)malloc(sizeof(int));
delete p1;  // ❌ malloc-delete 혼용
// ❌ 미정의 동작
int* p2 = new int(42);
free(p2);  // ❌ new-free 혼용
// ✅ 올바른 짝
int* p3 = (int*)malloc(sizeof(int));
free(p3);
int* p4 = new int(42);
delete p4;
auto p5 = std::make_unique<int>(42);
// 자동 해제

문제 2: new 후 예외 발생

증상: 메모리 누수

// ❌ 예외 발생 시 메모리 누수
void badFunction() {
    int* p = new int(42);
    
    // 예외 발생 가능
    if (true) {
        throw std::runtime_error("오류");
    }
    
    delete p;  // 실행 안 됨
}
// ✅ make_unique로 자동 해제
void goodFunction() {
    auto p = std::make_unique<int>(42);
    
    // 예외 발생 가능
    if (true) {
        throw std::runtime_error("오류");
    }
    
    // 예외 발생해도 자동 해제
}

문제 3: 배열 delete 누락

증상: 메모리 누수

// ❌ delete 사용 (배열은 delete[])
int* arr = new int[10];
delete arr;  // ❌ 메모리 누수 가능
// ✅ delete[] 사용
int* arr2 = new int[10];
delete[] arr2;
// ✅ make_unique 사용
auto arr3 = std::make_unique<int[]>(10);
// 자동 해제

문제 4: 함수 인자로 전달

증상: 소유권 혼란

// ❌ raw 포인터로 전달 (소유권 불명확)
void process(int* ptr) {
    // delete ptr?  // 누가 해제?
}
int* p = new int(42);
process(p);
delete p;  // 여기서 해제?
// ✅ unique_ptr로 전달 (소유권 이전)
void process2(std::unique_ptr<int> ptr) {
    // 자동 해제
}
auto p2 = std::make_unique<int>(42);
process2(std::move(p2));  // 소유권 이전
// p2는 nullptr
// ✅ raw 포인터로 전달 (소유권 유지)
void process3(int* ptr) {
    // 읽기만
}
auto p3 = std::make_unique<int>(42);
process3(p3.get());  // 소유권 유지

마무리

현대 C++에서는 make_unique를 사용하세요.

핵심 요약

  1. malloc vs new vs make_unique
    • malloc: 생성자 호출 안 함, free 필요
    • new: 생성자 호출, delete 필요
    • make_unique: 생성자 호출 + 자동 해제
  2. 선택 기준
    • 일반적인 경우: make_unique
    • 공유 소유권: make_shared
    • C 라이브러리 연동: malloc
    • 레거시 코드: new
  3. 예외 안전성
    • malloc/new: 예외 발생 시 메모리 누수
    • make_unique: 자동 해제로 안전
  4. 성능
    • 거의 차이 없음
    • 안전성이 더 중요

선택 가이드

상황권장이유
C++ 객체make_unique자동 해제
공유 소유권make_shared참조 카운팅
C 라이브러리mallocC 호환
레거시 코드new기존 코드 유지
일반적인 경우make_unique예외 안전

코드 예제 치트시트

// malloc
int* p1 = (int*)malloc(sizeof(int));
*p1 = 42;
free(p1);
// new
int* p2 = new int(42);
delete p2;
// make_unique
auto p3 = std::make_unique<int>(42);
// 자동 해제
// 배열
auto arr1 = std::make_unique<int[]>(10);
// 커스텀 삭제자
std::unique_ptr<int, decltype(&free)> p4((int*)malloc(sizeof(int)), free);

다음 단계

참고 자료

  • “Effective Modern C++” - Scott Meyers
  • “C++ Primer” - Stanley Lippman
  • cppreference: https://en.cppreference.com/w/cpp/memory 한 줄 정리: 현대 C++에서는 make_unique로 자동 해제와 예외 안전성을 보장하고, C 라이브러리 연동 시에만 malloc을 사용한다.

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ malloc vs new vs make_unique | 메모리 할당 완벽 비교」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ malloc vs new vs make_unique | 메모리 할당 완벽 비교」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. C++ malloc vs new vs make_unique: 메모리 할당 완벽 비교. malloc vs new vs make_unique 차이·생성자 호출·예외 안전성·RAII로 흐름을 잡고 원리·코드·실무 적용을 … 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, malloc, new, make_unique, 메모리할당, RAII, 스마트포인터 등으로 검색하시면 이 글이 도움이 됩니다.