Reputation: 13
Here's goes my first attempt at a question on stackoverflow -
I have the following implemented in C:
When running my program, I have realized that the value of hashstring printed out differs in the two following functions:
void foo() {
...
Obj *obj = Obj(args);
char *hashstring = getHash(obj);
printf("My value of hashstring: %s\n", hashstring);
...
}
char* getHash(Obj *obj) {
...
int hashint = getHashInt(args);
// I am trying to do a conversion from int to string here
char hashstring[12];
sprintf(hashstring, "%d", hashint);
printf("My value of hashstring: %s\n", &hashstring);
return &hashstring;
}
Here's what gets printed out:
My value of hashstring: 1001 // printing in getHash: this is the expected
My value of hashstring: 0
My value of hashstring: 2002 // printing in getHash: this is the expected
My value of hashstring: 0
My value of hashstring: 3003 // printing in getHash: this is the expected
My value of hashstring: 0
I have tried debugging by printing the pointer of hashstring instead, in foo(). It seems like in every single call, I am getting the same address for hashstring.
Here's what gets printed out:
0x7ffee1992f54
0x7ffee1992f54
0x7ffee1992f54
I guessed that this probably meant that I am somehow referencing the same hashstring variable in getHash(), which is strange since I am creating a new variable each time. I have also tried other variants like snprintf(hashstring, 12, "%d", hashint) in getHash(), or creating a char *pointerToHash and passing in *pointerToHash to sprintf.
Any ideas?
Upvotes: 1
Views: 536
Reputation: 311126
This function
char* getHash(Obj *obj) {
...
int hashint = getHashInt(args);
// I am trying to do a conversion from int to string here
char hashstring[12];
sprintf(hashstring, "%d", hashint);
printf("My value of hashstring: %s\n", &hashstring);
return &hashstring;
}
invokes undefined behavior because it returns a pointer to the local array
char hashstring[12];
that will not be alive after exiting the function.
Moreover the return type of the function char *
and the type of the returned expression char ( * )[12]
are different and there is no implicit conversion from one type to another.
To avoid the problem you should allocate the array dynamically like for example
char *hashstring = calloc( 12, sizeof( char ) );
and in the return statement write
return hashstring;
Then in the caller you should free the allocated memory when the allocated array will not be needed any more.
Upvotes: 1