2014-03-06 3 views
0

토큰 문자 포인터를 다시 할당하는 데 문제가 있다고 생각하십시오. 도와주세요. 내가 realloc하는 방법을 googged하지만 내 프로그램을 실행할 때 메모리 부실 오류가 발생하기 때문에 이것이 올바른 방법인지 확실하지 않습니다.C에서 메모리 재 할당

char* token = (char*)malloc(sizeof(char)); 
token[0] = '\0'; 
int c; 
do{   
    c = fgetc(fp); 
    if(isalnum(c)){ //add to char array 
     if(isalpha(c)) 
      c = tolower(c); 
     if(token[0] == '\0'){ 
      token[0] = (char)c; 
      token[1] = '\0'; 
     } 
     else{ 
      token = (char*)realloc(token, strlen(token)+2); 
      int len = strlen(token); 
      token[len] = (char)c; 
      token[len+1] = '\0'; 
     } 
    } 
    else{ //token 
     if(token[0] != '\0'){ //add token 
      struct token* newtoken = (struct token*)malloc(sizeof(struct token)); 
      newtoken->token = (char*)malloc(strlen(token)*sizeof(char)); 
      strcpy(newtoken->token, token); 
      newtoken->records = NULL; 
      struct record* newrecord = (struct record*)malloc(sizeof(struct record)); 
      newrecord->fileName = (char*)malloc(strlen(fileName)*sizeof(char)); 
      strcpy(newrecord->fileName, fileName); 
      newrecord->freq = 1; 
      tokens = (struct token*)addToken(tokens, newtoken, newrecord); 
     } 
     token[0] = '\0'; 
    } 
    if(feof(fp)) 
     break; 
}while(1); 
+0

첫 번째 malloc은 1 문자 씩만 공간을 할당합니다. 네가 적어도 2자를 원한다고 생각해. –

+0

하나의 명백한 문제 :'strlen'은 널 종료 문자를 포함하지 않으므로'strcpy' 전에'strlen (s) + 1'을 할당해야합니다. 'malloc' 전에는 지저분한 캐스트가 필요 없습니다. –

+0

'char * token = (char *) malloc (sizeof (char));'이게 맞을까요? sizeof (char)는 항상 ** 1 **이므로'token [1]'에 접근하면 문제가 생길 것입니다 ... – Naytzyrhc

답변

1

당신이 쓴 :

더 명확하게 char *token = malloc(1);로 표현
char* token = (char*)malloc(sizeof(char)); 

, 이것은 1 바이트를 할당합니다.

하지만 당신은 이동 : 1 바이트 할당에 2 바이트를 기록

token[0] = (char)c; 
token[1] = '\0'; 

. 이것은 버퍼 오버 플로우이며 메모리 손상의 원인 일 수 있습니다. 당신은 2 바이트를 malloc으로 시작하여이 문제를 해결할 수 있습니다.

newtoken->token = (char*)malloc(strlen(token)*sizeof(char)); 
strcpy(newtoken->token, token); 

변경에 :

또한 나중에 버퍼를 덮어

newtoken->token = malloc(strlen(token) + 1); 
strcpy(newtoken->token, token); 

내 버전도 당신보다 적은 사마귀를 얼마나 공지 사항, 그래서 쉽게 읽을 수 및 발견하는 것이 더 쉽다 오류가있는 경우.

그 다음으로는 strcpy도 같은 문제가 있습니다.