0

When I try to use a pointer to short, I get undefined behavior or segmentation fault.

For example:

#include <stdio.h>

int main() {
    short int *a;
    *a = 10;
    printf("%hd\n", *a);
    return 0;
}

Nothing is displayed on the command line.

So I can`t understand how can I properly work with it.

  • You must know more about pointers to understand it well. – Lion King Aug 20 '23 at 19:25
  • 1
    If somebody gives you a blank piece of paper on which you can write a street address, do you automatically own a house? – Eric Postpischil Aug 20 '23 at 19:38
  • Your compiler might give you some hint regarding "using variable a without assigning a value first". If not, you should increase warning level. If it does, don't ignore what your compiler tells you. – Gerhardh Aug 21 '23 at 08:24

1 Answers1

4

That's because a is only a pointer but there is no memory allocated. It's also uninitialized, so reading it (*a) makes the program have undefined behavior.

You can malloc memory:

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

int main() {
    short int *a = malloc(sizeof *a);
    if (a == NULL) return 1;

    *a = 10;
    printf("%hd\n", *a);

    free(a);
}

or make it point at an automatic variable:

#include <stdio.h>

int main() {
    short int some_short_int; // automatic variable

    short int *a = &some_short_int;
    *a = 10;
    printf("%hd\n", some_short_int); // prints 10
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108