所以我有一個問題,我有一個char * s(聲明爲)char **數組是動態分配的數組(由calloc),但char * s內它是靜態的。釋放一個靜態字符串的動態數組
,直到我試圖釋放陣列(調整大小時)也能正常工作對我來說,在這一點上,我得到
*** glibc detected *** ./hash_table_test: free(): invalid next size (normal): 0x0891f028 ***
我試圖將所有的師生比的陣列爲NULL,但後來我得到了錯誤
*** glibc detected *** ./hash_table_test: double free or corruption (!prev): 0x0815b028 ***
下面是相關代碼:
表結構:
struct string_hash_table {
//Array of c-strings
char** table;
//number of elements in the table
int num_elements;
//size of table
int table_size;
//Primes
int *primes;
//Current position in primes array
int primes_index;
//the size of the primes array
int primes_size;
};
//TypeDefs--------------------------------
typedef struct string_hash_table HashTable;
翻版功能(錯誤的來源)
void rehash_string(HashTable *table) {
int prev_size = table->table_size;
int i;
table->table_size = table->table_size * 2;
//create new array
char** new_table = calloc(table->table_size, sizeof(char*));
printf("new table created\n");
int index;
printf("before loop prev_size is %d\n", prev_size);
//add all elements to new_table
for (i = 0; i < prev_size; i++) {
printf("on %d\n", i);
index = find_spot_string(new_table, table->table_size, table->table[i]);
printf("after find_spot_string\n");
if (index != -1) {
table->table[index] = table->table[i];
}
}
//free and swap
printf("before free\n");
empty_string_array(table->table, table->table_size);
free(table->table);
table->table = new_table;
初始化哈希表結構的:
//Takes a HashTable and initializes it
void init_hash_table(HashTable *table) {
table->primes_index = 0;
table->num_elements = 0;
table->primes_size = 297;
table->primes = prime_list;
table->table_size = table->primes[0];
table->table = calloc(table->table_size, sizeof(char*));
}
內的靜態字符串聲明:
char* temp = "hello";
add_hash_table_string(table, temp);
temp = "luck";
add_hash_table_string(table, temp);
temp = "stuck";
add_hash_table_string(table, temp);
temp = "buck";
add_hash_table_string(table, temp);
temp = "muck";
add_hash_table_string(table, temp);
temp = "much";
add_hash_table_string(table, temp);
目前我只是測試我的代碼在這裏,除了上面的重新哈希函數,一切都可以工作。有人有主意嗎?或我應該遵循的主角?
編輯:添加代碼爲add_hash_table_string
void add_hash_table_string(HashTable *table, char* element) {
//if non-null element, and element is not in the HashTable
if (element != NULL && contains_hash_table_string(table, element) == 1) {
//if the table is full
if (table->table_size/2 < table->num_elements) {
rehash_string(table);
}
int index = find_spot_string(table->table, table->table_size, element);
table->table[index] = element;
table->num_elements++;
}
}
EDIT2:
忘記確切地說,誤差在翻版功能與遊離(表 - >表)中的線中發生
神聖的降壓...... –
你正在使用函數'add_hash_table_string()',我們應該猜測它是什麼以及你的代碼出錯了嗎?你需要提供一個SSCCE([Short,Self-Contained,Correct Example](http://sscce.org/)),以便人們可以提供幫助。或者你應該考慮使用['valgrind'](http://valgrind.org/)。 –
只有表是動態分配的,那麼'empty_string_array()'應該做什麼? – Arjor