2013-05-16 2 views
1

거대한 stdin이라는 단어가 가득 찬 프로그램을 작성하고 있습니다. 입력을 100 자까지의 문자열로 나누고 싶습니다. 그래서 여기에 내 코드가있다.realloc의 주소가 잘못되었습니다.

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

static char* string = "\0"; 

void getChar(char new){ 
    if (strcmp(string,"\0") == 0){ 
     free(string); 
     string = (char *) malloc(sizeof(char)); 
     if (string == NULL){ 
      exit(EXIT_FAILURE); 
     } 
     string[0] = new; 
    } else { 
     char* newString = (char*) realloc(string, sizeof(string)+sizeof(char)); 
     if (newString == NULL){ 
      exit(EXIT_FAILURE); 
     } 
     string = newString; 
     string[strlen(string)]=new; 
    } 
    if (strlen(string) > 100){ 
     printf("%s\n",string); 
     dosomething(string); 
     string = "\0"; 
    } 
} 

void getInput(){ 
    int temp; 
    while((temp = fgetc(stdin)) != EOF){ 
     getChar((char) temp); 
    } 
} 

int main(int argc, char *argv[]){ 
    getInput(); 
} 

내가 emmediately 말하는 오류가 컴파일하고 코드를 실행 한 후 : 이후 버전에서

*** glibc detected *** ./sort: realloc(): invalid next size: 0x08f02008 //ofc this address always changes 

, 내가 문자열이 100 개보다 큰 문자가 ingnored되고있는와 n \에 의해 필터링됩니다. 이 가리키는 것은 아닌 길이 (즉, string이 무엇인지 이후, 포인터)

+1

제안 : C 프로그램에서'new'와 같은 C++ 키워드를 피하십시오. –

답변

3

sizeof(string) 실제로 당신에게 string자체의 크기를 알려줍니다. strlen (항상 0 바이트가 종료되어야 함을 의미) 또는 별도의 길이 변수를 사용하여 문자열의 길이를 직접 추적해야합니다.

다른 버그가 많이 있습니다. 첫 번째 free(string)은 할당 된 공간에 string 포인트가 채우기 전에 발생합니다. 이는 치명적입니다.

+0

@TorhanBartel : 항상 0 바이트의 종료 문자 만 입력하면됩니다. 예를 들어'string [0] = new;'-하지만 한 문자 만 저장하면 문자열은 저장되지 않습니다. 그래서 당신은 * 그것에'strlen'을 사용할 수 없습니다. –

+0

그래, 문자열에 대한 메모리 addres가 필요 ... malloc main()에? –

+0

및 \ 0 문자를 설정해야합니다. –