-1

Hi I am learning about pointers in C and wondered what does the code below do? Does the pointer *abc just points to some random stuff because it is not properly assigned with an address of a variable?

   void func()
   {
      int *abc;
      *abc = 5;
   }
Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
JessZhu
  • 15
  • 1
  • 5
  • 2
    The code will simply invoke undefined behaviour when run. – George Aug 31 '19 at 19:12
  • 2
    It's undefined behavior, since you're assigning to the target of `abc` before you have assigned a pointer value to it. – Tom Karzes Aug 31 '19 at 19:12
  • Yes. It points to some random stuff. If it happens to point to valid memory you'll overwrite something else. If it is not you'll get a segmentation fault and the program will crash. – Gerardo Zinno Aug 31 '19 at 19:12
  • Until a pointer is initialized to point to a valid memory location, the pointer is an "*uninitialized pointer*" holding some indeterminate address as its value. When you assign a valid address to the pointer, you *initialize* the pointer to point to that valid address (*a pointer is just a normal variable that holds the memory address to something else as its value*, i.e. the pointer points to that address). So in your case if you have `int i = 5, *abc = &i;` you initialize `abc` (make it point) to the address in memory where `5` is stored. – David C. Rankin Aug 31 '19 at 20:40

2 Answers2

0

As you note, abc is not properly initialized, so we do not know what it points to. Before it can be reliably used, it must be assigned a value that is the address of properly reserved memory. You can assign it a value by assigning it the address of a defined object (as in int x; int *abc = &x;) or by requesting memory through a routine such as malloc (as in int *abc = malloc(sizeof *abc); and checking that the result is not NULL).

Note that it is not correct to say that it “points to random stuff.” In the terms of the C standard, its value is indeterminate. This means its value is not only unspecified, but that a program that uses it might behave as if abc has a different value each time it is used—it does not necessarily act as if abc has some single randomly determined value. It might also have a trap representation, which does not represent a value of pointer type, and using it would result in the behavior of the program not being defined by the C standard.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

You cannot assigning a value to pointer with assigning memory, which leads to segmentation fault.

int *abc;

Above statement will just declare a pointer to integer, but it does not hold any address.

int *abc = (int *)malloc(sizeof(int));
*abc = 5;

If you want to assign a value directly, You need to initialize with some memory. Only then you can assign directly

kaushik
  • 556
  • 1
  • 7
  • 22