PDA

View Full Version : problem returning MD5sum value using pointer from a sub function


bloodfire
10-23-2005, 06:38 AM
Here's the code:

char *getmd5(char* secureFile) {
FILE *hashstring;
char hashval[32], hashval1[32], hashop[100], junky[100];
snprintf(hashop, sizeof(hashop), "md5sum %s", secureFile);
hashstring = popen(hashop,"r");
fread(hashval,32,1,hashstring);
pclose(hashstring);
sscanf(hashval, "%s %s", hashval1, junky);
return(hashval1);
}


For 1 i'm very bad in using ptr*. But there seems to be no escape from it especially when using sub function. I would omit using sub-function but the problem is I require it in few other locations of the code, so would like to use it. If i don't use it, my code would have repetitions and small changes would result in searching for it anc changing all of them.

I will get weird symbols from the 31st character on words and sometimes I get segmentation fault.

What's seems to be the probem?

i3839
10-23-2005, 12:23 PM
All variables declared in a function are created on the stack and disappear when the function returns (except static variables).

So the quickest, and most ugly fix is to make hashval1 static. But then the value is overwritten everytime you all the function. A slight variant is to use a global variable for hashval1, that has exactly the same effect, but the ugliness is less hidden.

A better solution is to let the caller handle the memory, and let hashval1 be a pointer passed as a parameter to the function. Or, if you want to give the caller less choice, just malloc hashval1, and let he caller be responsible to free the memory when it isn't used anymore.