Firstly, if you have already assigned the address of the dynamically allocated memory to the source pointer, then in the function you should use the function realloc
instead of malloc
. Otherwise, you will have a memory leak.
To change a source pointer in a function, it must be passed by reference, that is, through a pointer to a pointer.
Below is a demonstration program.
#include <stdio.h> #include <stdlib.h> void f( int **p, size_t n ) { int *tmp = realloc( *p, n * sizeof( *tmp ) ); if ( !tmp ) { free( *p ); } else { for ( size_t i = 0; i < n; i++ ) tmp[i] = ( int )i; } *p = tmp; } int main(void) { size_t n = 5; int *a = malloc( n * sizeof( int ) ); for ( size_t i = 0; i < n; i++ ) a[i] = ( int )i; for ( size_t i = 0; i < n; i++ ) { printf( "%d ", a[i] ); } putchar( '\n' ); n *= 2; f( &a, n ); for ( size_t i = 0; i < n; i++ ) { printf( "%d ", a[i] ); } putchar( '\n' ); free( a ); return 0; }
Its output to the console:
0 1 2 3 4 0 1 2 3 4 5 6 7 8 9
In general, after exiting a function, you should check that the NULL pointer is not equal to avoid undefined behavior.
If you do not want to free up memory for an already allocated array in case of a memory redistribution within a function, then you can return a logical value from the function, indicating success or failure of memory allocation.
For example,
_Bool f( int **p, size_t n ) { int *tmp = realloc( *p, n * sizeof( *tmp ) ); _Bool success = tmp != NULL; if ( success ) { for ( size_t i = 0; i < n; i++ ) tmp[i] = ( int )i; *p = tmp; } return success; }
And there is no need to initialize the pointer as follows:
int* row_size = (int*)malloc(0);
It is enough to write initially
int* row_size = NULL;
void AbstractName(int** row_size){ ... *row_size = (int*)malloc(sizeof(int)*rows); ...}
void AbstractName(int** row_size){ ... *row_size = (int*)malloc(sizeof(int)*rows); ...}
and call...AbstractName(&row_size);...
- avpmalloc(0)
means ... - 0andriy