Non deterministic trivial C program -


If I write something inside my main function and I really do not understand, then the following C program has a different Output is ..

If we comment on my variable declaration, then everything is fine and we get the results we expect (apply 3 times SHA256 to 0x12345678). But, if I write something in the main function, the output changes and does not take the expected value.

Code (precompute.c):

  #include & lt; Stdlib.h & gt; # Include & lt; Stdio.h & gt; #include & lt; String.h & gt; # Include & lt; openssl / sha.h & gt; Unsigned char * sha256_3 (int * input) {char * s = (char *) input; Unsigned four * D = SHA256 (S, Stellon (S), 0); d = SHA256 (D, Stellon (D), 0); D = SHA256 (D, Stellon (D), 0); Return D; } Zero print_hash (unsigned char * d) {int i; For (i = 0; i & lt; SHA256_DIGEST_LENGTH; i ++) printf ("% 02x", d [i]); Putchar ('\ n'); } Int main (int argc, const char * argv []) {int A = 0x12345678; Unsigned char * b = sha256_3 (& amp; a); print_hash (b); // int myVariable = 3; // Repeat this line and recompile to see the difference return EXIT_SUCCESS; }    = $ (Source: .c = .o) XKTable = Hello all: $ (source) $ (executable) $ (executable): $ (objects) $ (cc) $ (objects) -a $ @ $ (LDFALGS). C .o: $ (cc) $ (cflagas) $ & lt; -O $ @ Clean: RM-RF * O Hello!   

Expected Output (Annotation of my variable annotation):

8f3d8f8c5eff23dc137762220cf24f140b7a1b804cc2044261742fd73286c169

An unexpected output (not declaring my variable):

663e9571f713f83b19c913938e2947c8fc0a7072d1fc442385857c456c43295b

Thanks a lot!

By analyzing this snippet:

  char * s = ( char *) input; Unsigned four * D = SHA256 (S, Stellon (S), 0);   

Some errors can be seen for input originally defined with an int (line with a int A ) Is an indicator. An int is usually 4 bytes. When you put a pointer in it four *, then ok, you tell the point in the allocated memory of 4 bytes. But, strlen () rely on the presence of a NUL ('\ 0') character at the end of all the function strings in string.h. Basically, how many letters are there to strlen () NUL, as you do not have a NUL character after those 4 bytes of Intel, the result can be found in memory (can be anywhere in 0, which is the value of the NUL character , And Stalin Stop). .

Now, to fix this, you have 2 possible solutions: either you create a string from the beginning with the values ​​required, or, in sha256_3 function, create 5 bytes of string, 4 people Assign NUL to the provided matrix and the previous one as a copy parameter.

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -