开发者

C - dynamic memory allocation using double pointer

开发者 https://www.devze.com 2023-03-11 05:47 出处:网络
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,

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.


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


char **ptr = 0;
foo( ptr );

You are passing the value that ptr points to. But you havent pointed ptr to anything yet.

*ptr = malloc(255);

Now you are assigning some memory to that "nothing". So this wont work, and will segfault. Why are you saying that this is another way of using double pointers? I apologise if I am wrong, but I guess you worked with type of program in Turbo-C earlier?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号