C - dynamic memory allocation using double pointer

I allocate some memory in the name of the myalloc () function and use it and freeing it in main (). I am using a double pointer to do this, here is the code that 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 the following code does not work and gives a segmentation error. 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 to me why it gives me a seg error in the second example.

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

In addition, I know that a question has already been asked about memory allocation using double pointers, but they do not address this problem, so please do not indicate this as a repeating question.

+4
source share
3 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 is ... 0 , which is not a writable memory.

ptr should indicate an address to which you can write. 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 
+10
source
 char **ptr = 0; foo( ptr ); 

You pass in the value pointed to by ptr. But you haven't pointed anything to ptr yet.

 *ptr = malloc(255); 

Now you assign some memory to this "nothing." So this will not work, and there will be a segfault. Why are you saying this is another way of using double pointers? I apologize if I am wrong, but I suppose you used to work with a program type in Turbo-C?

0
source

In the second case, you pass the value of the main ptr , which is 0 (NULL), to myalloc() ptr . myalloc() then tries to dereference the null pointer, ptr .

0
source

All Articles