Home > Software engineering >  is this correct use of pointer and memory allocation
is this correct use of pointer and memory allocation

Time:07-07

so This is my code that allocate 0th and 2ed string in 2-d array (list of strings, or a bucket) So I like to know did I use correct use of dynamic memory allocation with malloc and realloc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
    
int main(){
    
    char **a;
    printf("%zu\n",sizeof(*a));
    a = malloc(sizeof(*a)*3);
    a[0] = malloc(sizeof(char ) * 10);
    strcpy(a[0],"hello");
    printf("%s\n",a[0]);
    a[2] = malloc(sizeof(char) * 12);
    strcpy(a[2],"hello hello");
    printf("%s\n",a[2]);
    a[0] = realloc(a[0],18);
    strcpy(a[0],"hello hello hello");
    printf("%s\n",a[0]);
    
    return 0;
}

I like to knw can I jump from 0th string allocation to 2ed string allocation. is is valid in C/C

Like first I did

a[0] = malloc(sizeof(char ) * 10);

then

a[2] = malloc(sizeof(char) * 12);

missing 1st index allocation like

a[1] = malloc(sizeof(char) * 12);//didnt do 

CodePudding user response:

In general the code is unsafe because the second element stays uninitialized.

At least you should write

a[1] = NULL;

For example this allows to free the allocated memory in a loop.

for ( size_t i = 0; i < 3; i   )
{
    free( a[i] );
}

free( a );

Also this statement

a[0] = realloc(a[0],18);

is unsafe. You need to use an intermediate pointer like for example

char *tmp = realloc(a[0],18);
if ( tmp ) a[0] = tmp; 

Otherwise a memory leak can occur if the allocation will fail.

And in any case you should check whether allocations were successful.

  • Related