I'm working on a spell checking program for a class and am running into trouble trying to make the hash array accessible to other functions by using pointers.
Below is just a small part of the code since the program is too large to paste. Basic idea of this part of the code is:
-Create array and pointer to array. -Hash each word and use the value as index in array. -Use pointer to store the hashed value. -Access the array using the pointer for the array and hashed value.
As noted below, directly accessing the word stored in the array works, but I get a seg fault when trying to use the pointers to access the word stored in the array.
==1845== Invalid read of size 8
==1845== at 0x401367: load (dictionary.c:133)
==1845== by 0x40095D: main (speller.c:45)
==1845== Address 0xfffc3fab8 is not stack'd, malloc'd or (recently) free'd
char** hash_array = calloc(HASH_TABLE_SIZE, sizeof(*hash_array));
char*** array_pointer;
// storing the address of the hash array in pointer
array_pointer = &hash_array;
uint32_t* hash_pointer;
hash_pointer = NULL;
uint32_t hash = hashlittle(word_buffer, word_length, 1578459744);
hash_pointer = &hash;
// this prints out the word successfully
printf("word in h-array: %s\n", hash_array[hash]);
// this seg faults
printf("word in h-array: %s\n", *array_pointer[*hash_pointer]);
The issue you're seeing is because of the operator precedence of the dereference operator *
.
The following are all equivalent:
*array_pointer[*hash_pointer]
*array_pointer[hash]
*(array_pointer[hash])
*((&hash_array)[hash])
*(*(&hash_array + hash))
The problem is here: *(&hash_array + hash)
. You're attempting to dereference a pointer to some memory location offset from the location of where the pointer hash_array
is stored, rather than where it points, which is causing undefined behavior.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.