1

Here is a snippet of my code:

#include <stdio.h> #include "uhash.h" #include <openssl/evp.h> char * hash(item a) { const char * str= a.k; int len= strlen(str); int md_len; unsigned char md_value[EVP_MAX_MD_SIZE]; /* Buff to store change result */ EVP_MD_CTX *mdctx; /* Digest data structure declaration */ const EVP_MD *md; OpenSSL_add_all_digests(); md = EVP_get_digestbyname("SHA256"); mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, str, len); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); char md5str[33]; for(int i=0;i<md_len;++i) { sprintf(&md5str[i*2],"%02x",(unsigned int)md_value[i]); } printf("%s\n", md5str); return md5str; } int main(int argv, char **argc) { char *c; if (argv>0) { int i=0; int s=0; for(i=1;i<argv;i++) { s+=strlen(argc[i]); } c=(char *)(malloc(sizeof(char)*s*(argv-2)+1)); s=0; for(i=1;i<argv;i++) { char *t=c+s; memcpy(t,argc[i],strlen(argc[i])); if(i!=argv-1){ printf("%d\n", argv); t[strlen(argc[i])]=' '; s++; } s+=strlen(argc[i]); } *(c+s)='\0'; } printf("%s\n", c); item * kee= malloc(sizeof(item)); kee->k=c; kee->v=10; char *res= hash(*kee); fflush(stdout); if(res==NULL) printf("result is null..."); else printf("%s\n",res); fflush(stdout); } 

So the main function takes the arguments fine(tested) and passes it fine(tested) but the hash() function although computing the hash, does not either return the right value or I can't print the result in main. I've been trying to check for errors since yesterday but I'm not very smart so any help would be greatly appreciated!

2
  • 1
    The hash is probably a mix that includes non-printable characters and maybe '\0' too. I'd recommend scanning over the buffer and printing in hex -- but you need to know how many bytes there are in the res string. Commented Apr 11, 2014 at 16:22
  • @JonathanLeffler is likely right. If you can give us your header file as well (uhash.h) we may be able to provide further assistance. Commented Apr 11, 2014 at 16:51

1 Answer 1

2

Root cause: You are returning something that has been created on the stack and once it returns it is wiped. res is pointing into your stack.

Fix: Put the declaration of md5str outside the routine hash or make it static within the routine hash.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.