2015-01-13 2 views
0

이 줄에 버퍼 문제가 있습니다. strcpy_s (* (pWords + word_count), word_length, pWord); argv [1]에서 파일을 읽으려고하고 그 파일과 그 발생에있는 모든 단어를 인쇄하려고하는데, 뭐가 잘못 됐는지를 알 수는 없네요.?!?C strcpy_s - 버퍼가 너무 작음 && 0 오류

int main(int argc, char* argv[]) 
{ 
    char *delimiters = argv[2];      // Prose delimiters 
    char buf[BUF_LEN];          // Buffer for a line of keyboard input 
    size_t str_size = INIT_STR_EXT;       // Current memory to store prose 
    char* filePath = argv[1]; 
    FILE *fP ; 
    char* pStr = malloc(str_size);       // Pointer to prose to be tokenized 
    *pStr = '\0';           // Set 1st character to null 
    fopen_s(&fP, filePath, "r"); 
    fread(buf, BUF_LEN, 10, fP); 





    size_t maxWords = 10;          // Current maximum word count 
    int word_count = 0;          // Current word count 
    size_t word_length = 0;         // Current word length 
    char** pWords = calloc(maxWords, sizeof(char*));   // Stores pointers to the words 
    int* pnWord = calloc(maxWords, sizeof(int));    // Stores count for each word 

    size_t str_len = strnlen_s(buf, BUF_LEN);    // Length used by strtok_s() 
    char* ptr = NULL;           // Pointer used by strtok_s() 
    char* pWord = strtok_s(buf, delimiters, &ptr); // Find 1st word 

    if (!pWord) 
    { 
     printf("No words found. Ending program.\n"); 
     return 1; 
    } 

    bool new_word = true;          // False for an existing word 
    while (pWord) 
    { 
     // Check for existing word 
     for (int i = 0; i < word_count; ++i) 
     if (strcmp(*(pWords + i), pWord) == 0) 
     { 
      ++*(pnWord + i); 
      new_word = false; 
      break; 
     } 

     if (new_word)           // Not NULL if new word 
     { 
      //Check for sufficient memory 
      if (word_count == maxWords) 
      { // Get more space for pointers to words 
       maxWords += WORDS_INCR; 
       pWords = realloc(pWords, maxWords*sizeof(char*)); 

       // Get more space for word counts 
       pnWord = realloc(pnWord, maxWords*sizeof(int)); 
      } 

      // Found a new word so get memory for it and copy it there 
      word_length = ptr - pWord;  // Length of new word 
      *(pWords + word_count) = malloc(word_length);   
      strcpy_s(*(pWords + word_count), word_length, pWord); // Copy to array 
      *(pnWord + word_count++) = 1;       // Increment word count 
     } 
     else 
      new_word = true;          // Reset new word flag 

     pWord = strtok_s(NULL, delimiters, &ptr);  // Find subsequent word 
    } 
+0

당신은 모든 단어와 그 출현을 인쇄하려고합니다. 어떻게됩니까? – philant

+2

문제와 관련이 없지만 예를 들어 '* (pWords + i)'는'pWords [i]'와 동일합니까? IMHO는 특히 초보자에게 읽기 쉽고 이해하기 쉽습니다. –

답변

1

이 줄을 두 가지 문제가 있습니다 :

fread(buf, BUF_LEN, 10, fP); 

먼저 10 개의 요소를 읽으면 버퍼가 10 배로 작습니다.

둘째, BUF_LEN (이전에는 * 10)보다 파일을 읽지 않습니다.

argv[2] 구분 기호로 심지어 " \\n"으로 전달할 수 없기 때문에 코드는 newline 문자를 처리하지 않습니다.

fread()fgets() 루프로 바꾸고 구분 기호를 다시 정의하는 것이 좋습니다. 다른 사람이 주석으로

#define BUF_LEN 1000      // plenty of room 
... 
char buf[BUF_LEN+1];      // allow for 0 terminator 
char delimiters[] = " \n\t";    // predefined 
... 
//size_t str_len = strnlen_s(buf, BUF_LEN); // unnecessary 
while (fgets(buf, BUF_LEN, fP) != NULL) { // new outer loop 
    char* ptr = NULL;      // carry on as you were 
    ... 
} 

다음, 당신은 "안전"문자열 함수를 사용하고 있지만 당신이 argc을 확인하지 않았다, 문자열 공간 할당 또한

*(pWords + word_count) = malloc(word_length+1); 

을 늘리거나 어떤 결과 fopen_s(), fread(), malloc(), calloc(), realloc(), 파일을 닫지 않았거나 메모리를 해제하지 않았습니다.

+0

그 일은 고마워요! –

2

strcpy_s은 문자열 끝에 null 바이트를 추가합니다. malloc(word_length+1)이 필요합니다.

+0

도움이되지 않지만 여전히 같은 오류가 발생합니다. –

0

0 문자의 추가 바이트를 잊어 버린 것처럼 보입니다. 그럼에도 불구하고 대신 파일에 대한 고정 된 버퍼 크기를 할당, 당신은 SEEK_END를 사용 fseek과 함께 파일 크기를 얻을 수와는 할당 0의 오프셋 (offset)이 많은 메모리 + 1 바이트

관련 문제