c++ 참조 메모리 delete시 에러 발생

joyrae의 이미지

참조 메모리 해제시 에러가 발생하는데, 왜 그런건지 궁금합니다.

아래 코드에서 SetMemory를 2번 호출 시 에러가 발생하는데 왜 그런지 잘 모르겠습니다.

본문 코드

m_pchMemory = NULL;

for( int pos = 0; pos < 2; ++pos )
SetMemory(m_pchMemory);

아래는 SetMemory 함수 ---------------------
SetMemory(char *&memory) {
if( memory != null ) delete[] memory; <-- delete 시 에러 발생
memory = NULL; memory = new char[150];

memory[0] = 5;
memory[1] = 5;
memory[2] = 5;
}

klara의 이미지

'null'이 뭔가요?
실제 소스코드를 올리신거라면 NULL이 아닌 다른 값을 비교하고 계신거 같고,
실제 코드가 아니라 대충 여기에 적은 코드라면 실제 코드에 숨겨져 있을수 있는 실수를 찾을 수 없습니다.

몇가지 첨언하자면 C++에서는 NULL은 별로 의미가 없습니다.
C++의 NULL은 포인터 타입이 아닌 정수 0으로 정의됩니다.
C++11이상을 지원하는 환경이라면 nullptr을 사용하시는게 좋습니다.

그리고 delete 연산자를 사용할때 NULL 체크는 의미가 없습니다.
delete 연산자는 피연산자가 널 포인터일때 아무것도 하지 않습니다.

shint의 이미지


http://codepad.org/
C++ 선택

#include <stdio.h>
#include <stdlib.h>
 
 
void SetMemory(char * &memory)
{
    if( memory != NULL )
    {
        printf("1\n");
        delete[] memory;
    }
    printf("2\n");
    memory = NULL;
    memory = new char[150];
 
    memory[0] = 5;
    memory[1] = 5;
    memory[2] = 5;
}
 
int main()
{
    char * m_pchMemory = NULL;
 
    for( int pos = 0; pos < 2; ++pos )
    {
        SetMemory(m_pchMemory);
 
        if( m_pchMemory != NULL )
        {
            printf("%d %d %d\n", *(&m_pchMemory[0]), *(&m_pchMemory[1]), *(&m_pchMemory[2]));
        }
    }
 
    if( m_pchMemory != NULL )
    {
        printf("3\n");
        delete[] m_pchMemory;
    }
    return 0;
}

Output:
2
5 5 5
1
2
5 5 5
3

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.