Copy array to dynamically allocated memory

I got my code, but it seems to me that there is a faster way to do this, especially in my copy of the function. here is my code. could it be faster? this is in C btw. Also, when I return cpy from a function, does it delete dynamic memory from the moment of its absence? I do not want to have a memory leak: 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;
}
+3
source share
3 answers

You can replace forwith memcpy.

memcpy(cpy, a, ele * sizeof *cpy);

Also, what you are doing is pretty good: you are returning a pointer, so the caller has the option of freeit.

I also consider it a good practice NOT to call freeif you are about to exit - the OS will still collect memory.

+5

Memcpy. , .. .: -)

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;
}
+4

-

, : , , - , ; , , , malloc-ed malloc-ed, .

, , . , : free , : free(ptr); . , , .

Please also note that if the memory is automatically freed when the pointer to it goes out of scope, it will be freed from the copy function itself and you will return an invalid pointer; and then there would be many double free and identical, every time the pointer goes beyond! Fortunately, this does not happen, since the memory you got with malloc should be explicitly freed with free.

+2
source

All Articles