Segmentation fault when using qsort and printf

偶尔善良 提交于 2020-01-25 20:58:06

问题


I'm trying to make a program to crack passwords by searching through a file of md5 hashes and using bsearch to find them in a rockyou database. My problem is that I'm running into a segmentation fault that is either caused by my qsort or my printf (I've run Valgrind and it says printf, but manipulating qsort changes the error output). I can't seem to find the solution online, though I've tried flushing stdout and different ways to size the array in the qsort function.

char **dict = read_dict( argv[2] );

read_dict, which I haven't placed here because it's a hefty chunk of code, takes in the dictionary file, splits it into an array of strings, formats it into hash:password, and mallocs the space for it. It then returns the pointer of the array of pointers that contains each string.

int qcompare( const void *a, const void *b)
  {
  return strncmp( *((char **)a), *((char **)b), HASH_LEN);
  }

qsort(dict, (sizeof(dict) / sizeof(dict[0])), sizeof(char *), qcompare);

for (int i = 0; dict[i] != NULL; i++)
    {
    printf("%s\n", dict[i]);
    }

The printf shown here isn't the actual one I'm using, it's just a simpler one I was trying to use to debug my code. It's my first time posting so hopefully I haven't done anything atrociously wrong with formatting this question. Thank you in advance for any help I get.

read_dict as requested

 char **read_dict(char *filename)
 {
 FILE *f = fopen(filename, "r");
 if (!f)
    {
    printf("read_dict: file error message\n");
    exit(1);
    }

int arrlen = 0;
int i =  0;
char **dict = NULL;
char buf[PASS_LEN];
while (fgets(buf, PASS_LEN, f) != NULL)
    {
    if (i == arrlen)
        {
        arrlen += STEPSIZE;
        char **newdict = realloc(dict, arrlen * sizeof(char*));
        if (!newdict)
            {
            printf("read_dict: newdict error message\n");
            exit(1);
            }
        dict = newdict;
        }// end of if

    buf[strlen(buf) - 1] = '\0';
    int slen = strlen(buf);
    char *pass = malloc( (slen + 1) * sizeof(char));
    strcpy(pass, buf);

    char output[(HASH_LEN + PASS_LEN + 1)];
    sprintf(output, "%s:%s", md5(pass, strlen(pass)), pass );

    dict[i] = output;
    i++;
    }// end of while

if (i == arrlen)
    {
    char **newarr = realloc(dict, (arrlen + 1) * sizeof(char*));
    if (!newarr)
        {
        printf("read_dict: newarr error message\n");
        exit(1);
        }
    dict = newarr;
    }

dict[i] = NULL;
return dict;
}// end of read_dict

来源:https://stackoverflow.com/questions/43579318/segmentation-fault-when-using-qsort-and-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!