简体   繁体   中英

Segmentation Fault

So I need to make a specific hashcode function that meets a specific algorithm. The algorithm isn't really important in the context of this question. I'm getting a seg fault and am not sure how to fix it. I debugged it in gdb and found out it's from accessing an invalid memory address.

here's my code:

int hash_code(const char* str){
   int len = strlen(str);
   char* dst;
   if(len == 0 )
   return 0;
 else{
   strncpy(dst, str, (len - 1));
   return (hash_code(dst) * 65599) + str[len-1];
  }
}

I'm pretty confident that it's from the dst, but I'm not sure how to work around it, to not get the seg fault. What would I use or initialize dst with to avoid this?

strncpy does not null-terminate its output if the buffer is too small. For this reason, many people consider it a poor choice of function in almost all circumstances.

Your code has another problem in that dst does not point anywhere, but you try to write characters through it. Where do you imagine those characters are going? Likely this causes your segfault, trying to write characters to a random memory location that you have not allocated.

Assuming you want to stick with the recursive approach: Instead of making a copy of the string every time, change your function to pass the length of the string. Then you don't need to allocate any memory, nor waste any time calling strlen :

unsigned int hash_code(const char *str, size_t len)
{
    if ( len == 0 )
        return 0;

    return hash_code(str, len - 1) * 65599 + str[len - 1];
}

Note - to avoid integer overflow problems, use an unsigned type for the hash value.

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