2014-11-19 2 views
1

이 프로그램이 모든 입력에 대해 작동하지 않는 이유는 무엇입니까? Xcode6 오류 메시지를 생성 (입력 읽어서 역순으로 출력) hw5 (14536,0x7fff7c23f310)의 malloc : * 객체 0x100103aa0 대한 에러 : 포인터 realloc'd되고이 *가 malloc_error_break 중단 점을 설정할 할당되지 디버그하려면 불행히도 나는 이것을 이해하지 못합니다.C에서의 Realloc 및 NULL 포인터

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    char *input; 
    unsigned long long index; 
    input = malloc(1); 

    for (index = 0; (input[index] = getchar()) != EOF; index++) 
    { 
    if (input == NULL) 
    { 
     free(input); 
     printf("Error: Out of memory!\n"); 
     return 0; 
    } 
    realloc(input, index + 2); 
    } 

    for (index = index - 1; index != 0; index--) 
    { 
    putchar(input[index]); 
    } 
    printf("\n"); 

    free(input); 

    return 0; 
} 
+0

코드에 잠재적 인 [* 정의되지 않은 동작 *] (http://en.wikipedia.org/wiki/Undefined_behavior)이 있습니다. 초기의'malloc'이 실패한다면? 그렇다면'input'은'NULL'이 될 것입니다. 그러나 당신은 여전히 ​​역 참조를합니다. –

+0

문제에 관해서는 [realloc 참조] (http://en.cppreference.com/w/c/memory/realloc)를 읽어보십시오. –

+0

출력에 인덱스 [0] 문자가 없으므로 출력이 올바르지 않습니다. 따라서 루프 조건을 두 번째로 (index> = 0) 변경할 수 있습니다. –

답변

3

realloc()은 새 개체에 대한 포인터를 반환합니다. realloc()이 메모리를 재 할당하지 못하면 NULL이 반환되고 input은 유효하기 때문에 임시 변수를 사용하고 있습니다.

char* temp = realloc(input, index + 2); 
if(!temp) 
{ 
    //deal with error ... 
} 

input = temp ;