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);
첫 번째 malloc은 1 문자 씩만 공간을 할당합니다. 네가 적어도 2자를 원한다고 생각해. –
하나의 명백한 문제 :'strlen'은 널 종료 문자를 포함하지 않으므로'strcpy' 전에'strlen (s) + 1'을 할당해야합니다. 'malloc' 전에는 지저분한 캐스트가 필요 없습니다. –
'char * token = (char *) malloc (sizeof (char));'이게 맞을까요? sizeof (char)는 항상 ** 1 **이므로'token [1]'에 접근하면 문제가 생길 것입니다 ... – Naytzyrhc