2016-03-14 4 views
-3

Привет, я делаю проект, где мне нужно реализовать hashTable, который хранит слова на основе хэш-функции. На стресс-теста я получаю таНос(): повреждение памятиmalloc(): повреждение памяти при конкатенации строк

Начальная декларация Хеш

hashTable = (char**)malloc(hashSize[0] * sizeof(char*)); 

Это функция я написал, чтобы добавить слово в hashTable из hashSize:

void addWord(char** hashTable, unsigned int hashSize, const char* word) { 

    int bucketIndex = hash(word, hashSize); 
    //printf("Word to add = %s, bucket = %d, hashTable size = %d\n", word, bucketIndex, hashSize); 
    if(hashTable[bucketIndex] == NULL) { 
     hashTable[bucketIndex] = (char*)malloc(strlen(word) * sizeof(char)); 
     strcpy(hashTable[bucketIndex], word); 
     return; 
    } 
    /* checks for duplicats */ 
    int exists = 0;  
    char* heyStack = (char*)malloc(strlen(hashTable[bucketIndex])); 
    memcpy(heyStack, hashTable[bucketIndex], strlen(hashTable[bucketIndex])); 
    char* token = strtok(heyStack, " "); 
    while(token) { 
     if(strcmp(token, word) == 0) { 
      exists = 1; 
      break; 
     } 
     token = strtok(NULL, " "); 
    } 
    /* end check for duplicates */ 
    if(exists == 0) { 
     size_t bucketSize = strlen(hashTable[bucketIndex]); 
     hashTable[bucketIndex] = (char*)realloc(hashTable[bucketIndex], bucketSize + strlen(word) + 2); 
     memcpy(hashTable[bucketIndex] + bucketSize, " ", 1); 
     memcpy(hashTable[bucketIndex] + bucketSize + 1, word, strlen(word) + 1); 

    } 
} 

У меня есть стресс-тест, который добавляет 20k слов к столу, и он всегда разбивается на одно и то же слово (нет 10k)

Любые идеи о том, что я делаю неправильно?

Tyvm

+1

'malloc (strlen (word) * sizeof (char)", за которым следует 'strcpy'. Вы должны выделить еще один байт для терминатора' nul'. –

+0

добавил дополнительный байт для нулевого терминатора. Проблема остается – user1840302

+0

I я не уверен, что вы делаете с 'heyStack'. Вы выделяете память на основе' strlen' (без лишнего байта), но тогда вы 'memcpy'. Оставляет ли это ограничение на строку? –

ответ

0

Вы должны прекратить «ниточки» перед передачей его функций, которые имеют дело со строками, такие как strlen() и strtok().

  • Выделите размер строки и еще один байт для прекращения нулевого символа.
  • Завершите «строки», добавив нулевой символ.

Примечания:

Исправленный код:

void addWord(char** hashTable, unsigned int hashSize, const char* word) { 

    int bucketIndex = hash(word, hashSize); 
    //printf("Word to add = %s, bucket = %d, hashTable size = %d\n", word, bucketIndex, hashSize); 
    if(hashTable[bucketIndex] == NULL) { 
     size_t wordSize = strlen(word); 
     hashTable[bucketIndex] = malloc(wordSize + 1); /* size +1 */ 
     memcpy(hashTable[bucketIndex], word, wordSize + 1); /* why did you use strcpy() only in here? */ 
     return; 
    } 
    /* checks for duplicats */ 
    int exists = 0; 
    size_t dataSize = strlen(hashTable[bucketIndex]); 
    char* heyStack = malloc(dataSize + 1); /* size +1 */ 
    memcpy(heyStack, hashTable[bucketIndex], dataSize + 1); /* size +1 */ 
    char* token = strtok(heyStack, " "); 
    while(token) { 
     if(strcmp(token, word) == 0) { 
      exists = 1; 
      break; 
     } 
     token = strtok(NULL, " "); 
    } 
    /* end check for duplicates */ 
    if(exists == 0) { 
     size_t bucketSize = strlen(hashTable[bucketIndex]); 
     size_t wordSize = strlen(word); 
     hashTable[bucketIndex] = realloc(hashTable[bucketIndex], bucketSize + wordSize + 2); 
     memcpy(hashTable[bucketIndex] + bucketSize, " ", 1); 
     memcpy(hashTable[bucketIndex] + bucketSize + 1, word, wordSize + 1); 
    } 
    free(heyStack); /* do free what you allocated */ 
} 

Этот код будет лучше, если добавить некоторый код, чтобы проверить, если malloc() и realloc() успешны.