Question

Generally what I have to do? I should always initialize ptr?

char *ptr;

ptr = malloc (10);

OR

char *ptr = NULL ;

ptr = malloc (10);

And in a function?

void func(char **ptr)
{
    *ptr = malloc(10);
}

int main()
{
    char *ptr; /* OR char *ptr = NULL; ? */

    func(&ptr);

    return 0;
}
Was it helpful?

Solution

Initialize before using it.

Note, Assigning is also a initialization.

So,

char *ptr;

ptr = malloc (10);

is OK.

But in case of

void func(char **ptr)
{
    *ptr = malloc(10);
}

int main()
{
    char *ptr; /* OR char *ptr = NULL; ? */

    func(&ptr);

   return 0;
}

You should initialize as you may not know what the function will do with the pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top