简体   繁体   中英

My pointer is changing address erroneously

I have a very simple C program. My program uses a very simple hash file I created. Here is my hash file:

const int SIZE = 26;

// A is 65 through Y is 89
int get_index(char key) {
   return ((int) key) - 65;
}

void reset_hash(int* hash) {
   int i = 0;
   for (; i < (SIZE - 1); i++) {
      hash[i] = 0;
   }
   hash[SIZE -1] = '\0';
}

int get_value(int* hash, char key) {
   return hash[get_index(key)];
}

void increment_value(int* hash, char key, int value) {
   hash[get_index(key)] = ++value;
}

If absolutely necessary, I can explain why my hash function is so simple. I did not deem that necessary at this point but I can tell you that my domain is very simple and constant, that is why this hashing algorithm works well.

Now, the hash is created once from the main of another file:

int* hash = calloc(SIZE_OF_AC, sizeof(int));

and the following operations are called from the same file in various orders:

reset_hash(hash);
get_value(hash, /* some character here */);
increment_value(hash, /* some character here */, value);

I am also passing the hash pointer around several times, and the two main target functions receive the hash argument as follows:

int* hash

The calling function just sends hash .

Now, I am printing the address of hash using:

printf("hash: %p\n", hash);

In one place in my main file, but is printed several times because the function is executed several times. Here is the output that I receive:

hash: 0x801010
hash: 0x801010
hash: 0x3100000000801010
Segmentation fault (core dumped)

My question is, why is the address of my hash seem to change? Under what conditions in c would the starting address of an int* change given the operations I declared above?

I apologize if you think that I am missing more vital information. Let me know and I will post more. Thank you for any response.

The index func seems to have an error no?

// A is 65 through Y is 89
int get_index(char key) {
   return ((int) key) - 65;
}

Should it be (int) (key - 65)?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM