在 C 中实现原始哈希函数时出现段错误

问题描述 投票:0回答:1

我正在尝试集成一个相当原始的“哈希”函数。我知道它不是加密安全的,它只是为了学习......

它编译但每次都会出现段错误...

我把第一个参数作为输入。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

unsigned int hash_pw(const char* p) {
    unsigned int i;
    unsigned int res = 0;

    for(i = 50; i > 45; i--) {
        res += p[i] * (50 - i);
    }

    return res;
}

int main (int argc, const char* argv[]) 
{
int asd = (int) malloc(50*sizeof(int));
asd = (unsigned int) hash_pw(argv[1]);
printf("%s\n", asd);
free(asd);

return 0;
}

c string pointers segmentation-fault malloc
1个回答
0
投票

主要问题:

1.

int asd = (int) malloc(50*sizeof(int));
asd = (unsigned int) hash_pw(argv[1]);
printf("%s\n", asd);
free(asd);

asd
是一个整数。您尝试将其用作“printf”函数中的指针。当您将指针分配给
int
时,调用 malloc 根本没有意义。拨打免费电话也是无效的

  1. for(i = 50;
    您的字符串可能不会超过 51 个字符,它可能会调用未定义的行为

阅读警告不要让他们沉默

<source>: In function 'main':
<source>:21:11: warning: initialization of 'int' from 'void *' makes integer from pointer without a cast [-Wint-conversion]
   21 | int asd = malloc(50*sizeof(int));
      |           ^~~~~~
<source>:23:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]
   23 | printf("%s\n", asd);
      |         ~^     ~~~
      |          |     |
      |          |     int
      |          char *
      |         %d
<source>:24:6: warning: passing argument 1 of 'free' makes pointer from integer without a cast [-Wint-conversion]
   24 | free(asd);
      |      ^~~
      |      |
      |      int
In file included from <source>:5:
/opt/compiler-explorer/arm/gcc-arm-none-eabi-11.2-2022.02/arm-none-eabi/include/stdlib.h:94:15: note: expected 'void *' but argument is of type 'int'
   94 | void    free (void *) _NOTHROW;
      |               ^~~~~~
<source>:19:15: warning: unused parameter 'argc' [-Wunused-parameter]
   19 | int main (int argc, const char* argv[])
      |           ~~~~^~~~
© www.soinside.com 2019 - 2024. All rights reserved.