I have an array named A that contains random floats, with its size anywhere in the range from [10000, 1000000]. This array is a randomly generated argument to my function, and in order to operate on it I am trying to preemptively append/pad it with 10000 zeros in an efficient manner. I am worried that appending A’s allocated memory will corrupt the heap, so instead I allocate new memory, memcopy A, and memset 10000 trailing floats in the new Array to 0.0.
void *ArrayPadder(float *A){
int pad = 10000;
float *Apadded = (float*)malloc((sizeof(A)+pad)*sizeof(float));
memcpy(Apadded, A, sizeof(A));
memset(Apadded+sizeof(A), 0.0, pad);
return Apadded;
}
Can anyone suggest a more efficient way of accomplishing this?
EDIT: Apologies for the delay but I added some clarification. The reason I can’t just pre-allocate the correct memory space (510000 floats) is because the array is actually of random size, containing random floats. I chose 500000 in an attempt to simplify the question, which is now fixed.
Not really a more efficient way, but a more accurate way:
as if the size of float is 4, your code only initializes the first
pad / sizeof(float) = 10000 / 4 = 2500 elementsNote that I used
0and not0.0as the second parameter, asmemsettakes an int and sets its (low byte) value to all of the bytes.