Copy array to dynamically allocated memory
Solution 1
You can replace your for
with a memcpy
.
memcpy(cpy, a, ele * sizeof *cpy);
Other than that what you're doing it pretty okay: you're returning a pointer, thus the caller has a chance to free
it.
Also I consider it good practice NOT to call free
if you're going to exit - the OS will collect the memory anyway.
Solution 2
Use Memcpy. It might be able to take advantage of your underlying hardware etc... No need to reinvent the wheel. :-)
void * memcpy ( void * destination, const void * source, size_t num );
double *copy(double a[], unsigned ele){
size_t size = sizeof(double)*ele ;
double *cpy= malloc(size);
memcpy( cpy, a, size ) ;
return cpy;
}
Solution 3
does it delete the dynamic memory since its out of scope
No, it doesn't: the only memory that goes out of scope is the one holding the pointer; you return the value of that pointer, and it's the only thing you need to access the memory you malloc-ed and which stays malloc-ed until you free it explicitly.
I don't want to have memory leaks
Memory leaks happen when you get memory that you won't release. Indeed, your code have a memory leak: you do not free
the memory the pointer is returned by copy: free(ptr);
at the end of your code. In this case, it does not matter too much, but it's a good practice to avoid to forget it.
Note also that if the memory would be freed automatically when a pointer to it goes out of scope, it would be freed from inside the copy function itself and you would return an invalid pointer; and then there would be a lot of double free and alike, each time a pointer goes out of scope! Fortunately this does not happen since memory you got using malloc must be explicitly freed with free.
Painguy
Updated on June 10, 2022Comments
-
Painguy almost 2 years
I got my code working, but i feel as if there is a faster way to do this especially in my function copy. here is my code. can this be any faster? this is in C btw. Also when i return cpy from the function does it delete the dynamic memory since its out of scope? I don't want to have memory leaks :P
#include <stdio.h> #include <stdlib.h> double *copy(double a[], unsigned ele); int main(){ double arr[8], *ptr; unsigned i=0; for(;i<7;i++){ scanf_s("%lf", &arr[i]); } ptr=copy(arr, 8); for(i=0;i<7; i++) printf("%f", ptr[i]); } double *copy(double a[], unsigned ele){ double *cpy= malloc(sizeof(double)*ele); int i=0; for(;i<ele; i++) cpy[i]=a[i]; return cpy; }