I have a function and want to return the unknown size string from function arguments like that:
int encrypt(const char *input, char *output)
{
output_len = generate_random(); // random output size
...
output = malloc(output_len);
memcpy(output, data, output_len);
return 0;
}
when I call the function like below out_buffer
is not change and is null
char *out_buffer;
encrypt(in_buffer, out_buffer);
I change my code and use the pointer to pointer like this:
int encrypt(const char *input, char **output)
{
output_len = generate_random(); // random output size
...
*(output) = malloc(output_len);
memcpy(output, data, output_len);
return 0;
}
....
char *out_buffer;
encrypt(in_buffer, &out_buffer);
But it does not work.
You forgot to put a *
before output
here:
memcpy(*output, data, output_len);
// ^
The program compiled without errors/warnings because memcpy
takes a void
pointer and any pointer type is compatible with void*
.
Bonus hint
Dont write *(output)
but just *output
. Though having the parenthesis is not wrong, but just odd.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.