1

Here is the code as shown below:

#include <stdio.h>
#include"sha256.h"
#include <string.h>

uint8_t hash256[32];

int main()
{

    printf("\nminerando bloco...\n");

    char entrada[50] = "Hello World";
    char *str;
    char sha256_str[65];
    int nonce = 0;

    int i;
    do {
        sprintf(str, "%d", nonce);
        strcat(str, entrada);

        sha256_simple((const uint8_t *)(str), strlen(str), hash256);
        for (i = 0; i < 32; ++i)
        {
            //printf("%02x", hash256[i]);
            snprintf(sha256_str + i *2, 2 + 1, "%02x", hash256[i]);
        }
        nonce++;
    } while (sha256_str[0] != '0' || sha256_str[1] != '0' || sha256_str[2] != '0' || sha256_str[3] != '0' || sha256_str[4] != '0'); //dificuldade 4

    printf("\nNONCE:\t%d", nonce);
    printf("\nDATA:\t%s", entrada);
    printf("\nHASH:\t%s\n", sha256_str);

    return 0;
}

When I run the program it gives me segmentation fault in here:

snprintf(sha256_str + i *2, 2 + 1, "%02x", hash256[i]);
Mathieu
  • 8,840
  • 7
  • 32
  • 45
Memz Buck
  • 11
  • 1
  • 3
    `str` is not initialized and don't point to any valid memory area – Mathieu Mar 28 '22 at 15:25
  • 1
    Why is `str` a pointer instead of an array? – Barmar Mar 28 '22 at 15:28
  • What is the canonical question for this? – Peter Mortensen Mar 28 '22 at 15:40
  • 1
    [The tag wiki](https://stackoverflow.com/tags/c/info) has *[Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer](https://stackoverflow.com/questions/37549594/)* - *"This question is meant to be used as reference for all frequently asked questions of the nature: Why do I get a mysterious crash or "segmentation fault" when I copy/scan data to the address where an uninitialised pointer points to?"* – Peter Mortensen Mar 28 '22 at 15:43

1 Answers1

0

str is uninitialized so it is not pointing to any valid memory.

Replace

   char *str;

by

   char str[256];
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
Mathieu
  • 8,840
  • 7
  • 32
  • 45