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.
source share