2

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;
}
synth
  • 65
  • 5

1 Answers1

2

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.

Dipto
  • 2,720
  • 2
  • 22
  • 42
  • 2
    Then in the 'function version' I must declare the pointer as `char *ptr = NULL;`? – synth Jan 19 '14 at 11:11
  • In this particular version it is not needed, but if you are speaking, you should initialize with NULL, and your function should check the pointer passes to it, for case if it should dereference, it should return an error if NULL is passed. It depends on the function. – Dipto Jan 19 '14 at 12:24