46

I am writing a custom "vector" struct. I do not understand why I'm getting a Warning: "one" may be used uninitialized here.

This is my vector.h file

#ifndef VECTOR_H
#define VECTOR_H

typedef struct Vector{
    int a;
    int b;
    int c;
}Vector;

#endif /* VECTOR_ */

The warning happens here on line one->a = 12

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include "vector.h"

int main(void){
    Vector* one;
    one->a = 12;
    one->b = 13;
    one->c = -11;
}
Davy M
  • 1,697
  • 4
  • 20
  • 27
Valentino Ru
  • 4,964
  • 12
  • 43
  • 78

4 Answers4

63

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

simonc
  • 41,632
  • 12
  • 85
  • 103
21

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
9

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

CJBS
  • 15,147
  • 6
  • 86
  • 135
plaknas
  • 274
  • 4
  • 15
1

This might not be the most professional solution, but instead of initialising it using malloc, you can also initialise it using new:

Vector *one = new Vector();

I personally find it more elegant.

Beth Long
  • 375
  • 3
  • 24