Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - dynamic memory allocation using double pointer

I am allocating some memory in a function name myalloc() and using and freeing it in main(). I am using double pointer to do this, here is the code which works fine,

//Example # 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void myalloc( char ** ptr)
{
    *ptr = malloc(255);
    strcpy( *ptr, "Hello World");
}

int main()
{
    char *ptr = 0;
    myalloc( &ptr );
    printf("String is %s\n", ptr);
    free(ptr);

    return 0;
}

But following code does not work and gives segmentation fault. I think this is another way to use double pointers.

//Example # 2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void myalloc( char ** ptr)
{
    *ptr = malloc(255);
    strcpy( *ptr, "Hello World");
}

int main()
{
    char **ptr = 0;
    myalloc( ptr );
    printf("String is %s\n", *ptr);
    free(*ptr);

    return 0;
}

Please clarify me, why it is giving me seg fault in second example.

Note: Language = C, Compiler = GCC 4.5.1, OS = Fedora Core 14

Also, i know that there are some question already been asked related to memory allocation using double pointers, but they don't address this issue, so please don't flag it as repetitive question.

like image 612
mannan Avatar asked Dec 27 '22 19:12

mannan


1 Answers

char **ptr = 0;
*ptr = malloc(255);

tries to write the pointer returned by malloc to the address(of type char*) pointed to by ptr. The address turns out to be ... 0, which is not writable memory.

ptr should point to an address you can write to. You can do one of the following:

char *stackPtr; // Pointer on the stack, value irrelevant (gets overwritten)
ptr = &stackPtr;
// or
char **ptr = alloca(sizeof(char*)); // Equivalent to above
// or
char **ptr = malloc(sizeof(char*)); // Allocate memory on the heap
// note that ptr can be 0 if heap allocation fails
like image 150
phihag Avatar answered Jan 14 '23 03:01

phihag