Question

when I create a pointer to certain struct, do I have to set it to NULL, then alloc it then use it? and why?

Was it helpful?

Solution

No, there is no requirement (as far as the language is concerned) to initialize a pointer variable to anything when declaring it. Thus

T* ptr;

is a valid declaration that introduces a variable named ptr with an indeterminate value. You can even use the variable in certain ways without first allocating anything or setting it to any specific value:

func(&ptr);

OTHER TIPS

No, you don't have to set it to NULL, but some consider it good practice as it gives a new pointer a value that makes it explicit it's not pointing at anything (yet).

If you are creating a pointer and then immediately assigning another value to it, then there's really not much value in setting it to NULL.

It is a good idea to set a pointer to NULL after you free the memory it was pointing to, though.

According to the C standard, not initializing an automatic storage variable leaves its value indeterminate.

You are definitely encouraged to set pointers to NULL whenever the alternative is your pointer having an indeterminate value. Usage of pointers with an indeterminate value is undefined behavior, a concept that you might not grasp properly if you're used to C programming and come from higher level languages.

Undefined behavior means that anything could happen, and this is a part of the C standard since the philosophy of C is letting the programmer have the burden to control things, instead of protecting him from his mistakes.

You want to avoid undefined behaviors in code: it is very hard to debug stuff when any behavior can occurr. It is not caught by a compiler, and your tests may always pass, leaving the bug unnoticed until it is very expensive to correct it.

If you do something like this:

char *p;
if(!p) puts("Pointer is NULL");

You don't actually know whether that if control will be true or false. This is extremely dangerous in large programs where you may declare your variable and then use it somewhere very far in space and time.

Same concept when you reference freed memory.

free(p);
printf("%s\n", p);
p = q;

You don't actually know what you're going to get with the last two statements. You can't test it properly, you cannot be sure of your outcome. Your code may seem to work because freed memory is recycled even if it may have been altered... you could even overwrite memory, or corrupt other variables that share the same memory. So you still have a bug that sooner or later will manifest itself and could be very hard to debug it.

If you set the pointer to NULL, you protect yourself from these dangerous situations: during your tests, your program will have a deterministic, predictable behavior that will fail fast and cheaply. You get a segfault, you catch the bug, you fix the bug. Clean and simple:

#include <stdio.h>
#include <stdlib.h>

int main(){
  char* q;
  if(!q) puts("This may or may not happen, who knows");
  q = malloc(10);
  free(q);
  printf("%s\n", q); // this is probably don't going to crash, but you still have a bug

  char* p = NULL;
  if(!p) puts("This is always going to happen");
  p = malloc(10);
  free(p);
  p = NULL;
  printf("%s\n", p); // this is always going to crash

  return 0;
}

So, when you initialize a pointer, especially in large programs, you want them to be explicitely initliazed or set to NULL. You don't want them to get an indeterminate value, never. I should say unless you know what you are doing, but I prefer never instead.

No, don't forget that initialization has to be to a null pointer at all. A very convenient idiom in modern C is to declare variables at their first use

T * ptr = malloc(sizeof *ptr);

This avoids you a lot of hussle of remembering the type and whether or not a variable is already initialized. Only if you don't know where (or even if) it is later initialized, then you definitively should initialize it to a null pointer.

So as a rule of thumb, always initialize variables to the appropriate value. The "proper 0 for the type" is always a good choice if you don't have a better one at hand. For all types, C is made like that, such that it works.

Not initializing a variable is premature optimization in most cases. Only go through your variables when you see that there is a real performance bottleneck, there. In particular if there is an assignment inside the same function before a use of the initial value, andy modern compiler will optimize you the initialization out. Think correctness of your program first.

You dont have to unless you dont want it to dangle a while. You know you should after freeing(defensive style).

You do not have to initialize to NULL. If you intend to allocate it immediately, you can skip it.

At can be useful for error handling like in the following example. In this case breaking to the end after p allocation would leave q uninitialized.

int func(void)
{
    char *p;
    char *q;

    p = malloc(100);
    if (!p)
        goto end;

    q = malloc(100);
    if (!q)
        goto end;

    /* Do something */

end:
    free(p);
    free(q);

    return 0;
}

Also, and this is my personal taste, allocate structs always with calloc. Strings may be allocated uninitialized with malloc

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