Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is this correct use of pointer and memory allocation

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading