These statements
test = (double*)malloc(5*sizeof(double));
test = arr1;
results in a memory leak because at first memory was allocated and its address was assigned to the pointer test and then the pointer test was reassigned with the address of the first element of the array arr1. So the address of the allocated memory was lost.
And you may reallocate only memory that early was dynamically allocated using malloc
, calloc
or realloc
.
Arrays do not have the assignment operator. You need to copy elements from one array to another. For example
test = (double*)malloc(5*sizeof(double));
memcpy( test, arr1, 5 * sizeof( double ) );
for(i=0;i<5;i++) printf("%lf ",test[i]);
Your program can look the following way
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( void )
{
double arr1[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
const size_t N1 = sizeof( arr1 ) / sizeof( *arr1 );
double arr2[] = { 1.0, 2.0 };
const size_t N2 = sizeof( arr2 ) / sizeof( *arr2 );
double *test = malloc( sizeof( arr1 ) );
if ( test != NULL )
{
memcpy( test, arr1, sizeof( arr1 ) );
for ( size_t i = 0; i < N1; i++ )
{
printf( "%f ", test[i] );
}
putchar( '\n' );
double *tmp = realloc( test, sizeof( arr2 ) );
if ( tmp != NULL )
{
test = tmp;
memcpy( test, arr2, sizeof( arr2 ) );
for ( size_t i = 0; i < N2; i++ )
{
printf( "%f ", test[i] );
}
putchar( '\n' );
}
free( test );
}
}
The program output is
1.000000 2.000000 3.000000 4.000000 5.000000
1.000000 2.000000
Pay attention to that you need to use an intermediate pointer to reallocate memory. Otherwise again there can be a memory leak if the memory will not be reallocated successfully.
And the length modifier l
in the format string "%lf"
in the calls of printf
is redundant and has no effect,