-2

Firstly, look at the following simple code:

char str[80] = "This is - my text - for test";
const char s[2] = "-";
char *token;
token = strtok(str, s);

while (token != NULL) {
    printf(" %s\n", token);   
    token = strtok(NULL, s);
}

The function strtok() returns the data type char* and as you seen we created a variable named token that variable not initialized.

Now, look at the next code:

char *buff;
int num = 500;
sprintf(buff, "%d", num);

The result of the previous code is an error uninitialized local variable 'buff'.
My question is, why in the first code does not occurs any problem, while, in the second code occurred an error ?

Lion King
  • 32,851
  • 25
  • 81
  • 143
  • `char* token = strtok(str, s);` – Pete Becker Aug 22 '16 at 01:20
  • @PeteBecker: That is for direct assignment. – Lion King Aug 22 '16 at 01:26
  • That is **initialization**. The original code creates `token` uninitialized, then **assigns** to it. For simple types like `int` and pointers the difference sometimes doesn't matter technically (provided you do the assignment right after creating the uninitialized variable), although the chance for mistakes is much higher. But for types whose constructors do significant work there's a big difference. – Pete Becker Aug 22 '16 at 12:19

1 Answers1

6

Because in the first snippet you do initialize the variable token, by calling strtok and assigning the result of the call to the variable.

In the second example you leave the variable buff uninitialized.

You can initialize a local variable with an actual initialization at definition. Or by assigning to the variable elsewhere. The important thing is that you do this initialization or assignment before you use the variable in any other way.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Is this `sprintf(buff....` considered as assignment or considered as usage. – Lion King Aug 22 '16 at 01:25
  • @LionKing The `sprintf` function writes to the memory ***pointed to*** by the first argument. It does not modify the actual pointer. It's definitely usage. If you are unsure, *always* initialize variable some way. – Some programmer dude Aug 22 '16 at 01:27
  • @LionKing `sprintf(buff...` makes a *copy* of `buff` (as a parameter) but `buff` has not been given a value. – Galik Aug 22 '16 at 01:32