Maybe this is an easy one but i could not find solution.
in function :
int function(char **data)
{
char data_new[542] = {.......};
memcpy(*data, data_new, sizeof(data_new));
return 1;
}
It does not work because *data is smaller size of data_new. How to properly increase the size of *data to be successful memcpy()? I don’t want to just do:
*data = data_new;
I want to copy the data to this area of memory where this pointer points.
I tried:
*data = (char*)realloc(*data, sizeof(data_new) * 2);
Thanks in advance.
6
How to copy char data to a smaller char already defined in memory?
You realloc():
// Error checking omitted
#include <stdio.h>
#include <stdlib.h>
// your original function with (almost) no changes
int function(char **data) {
char data_new[542] = "bar";
data_new[541] = 'Z'; // just to illustrate
*data = realloc(*data, 542); // realloc, would be better to receive the original size
// and have a way to send back the new size
memcpy(*data, data_new, sizeof(data_new));
return 1;
}
int main(void) {
char *foo = malloc(200);
function(&foo);
printf("%c%c%c ... %cn", foo[0], foo[1], foo[2], foo[541]);
free(foo);
return 0;
}
See https://ideone.com/v10p2S
4
This is how it worked:
int function(char **data)
{
char data_new[542] = {.......};
*data= (char*)realloc(*data, 560);
SecureZeroMemory(*data, 560);
memcpy(*data, data_new, 542);
return 1;
}
Thanks.
4