Reputation: 1005
First off, I know this should have been answered somewhere on SO but I just can't seem to find the correct post. So if it is a duplicate please point me to the post that answers this question and I will delete this.
I have a function that copies a string:
static int read_ad_content(json_t * root, char* content)
{
[.. stuff happens]
const char* tmp = json_string_value(json_content);
unsigned int size = strlen(tmp);
content = (char*)malloc(size + 1);
memcpy(content, tmp, size);
content[size] = '\0'; // <= I checked and content is NOT null here!
return 0;
}
And I call it like this in my main function:
char *ad_content;
if (read_ad_content(ad_json, ad_content) != 0)
{
log_err(argv, "Failed to extract information");
}
if (ad_content == NULL)
{
// <= I always end up here
}
I know this should be easy but I just don't know how to solve this.
Upvotes: 3
Views: 5555
Reputation: 3034
In C, parameters are passed by value. What you're doing isn't any different from:
void brokenMethod(int a){
a = 10;
}
int a = 0;
brokenMethod(a);
if(a == 0)
{
//always end up here!
}
Of course you'll always end up there. a was never modified! The value of a was passed to brokenMethod, which could've done anything it wanted but that's not going to affect the value of a in your outer scope.
If I want the method to fill in an int, I have to pass it a pointer to an int.
void fixedMethod(int* a)
{
*a = 10;
//Remember, you want to modify the thing being pointed at, not the thing doing the pointing!
//a = something; is going to have the exact same problem as the first example
}
int a = 0;
fixedMethod(&a);
if(a == 0)
{
//Better
}
The above example sticks a value into an int. In your case, if you want the method to fill in a pointer to an int then you'll have to pass it a pointer to a pointer to an int.
Sidebar: You may also find that methods which return values via parameters are difficult to reason about and more likely to contain bugs. If you're trying to return an pointer to an int, just have a method that returns a pointer to an int.
int* HonestMethod()
{
return pointer to whatever.
}
Upvotes: 3