-1

When I tried to run this below two codes. For the first one I got segmentation fault error. I don't know why ?

 void main() {
       int *c1;
       *c1=10;
       printf("%d\n", *c1);
       printf("%d\n", sizeof(c1));
       printf("%d\n", sizeof(*c1));
       printf("%d\n", c1);
    }

When I run this below code, it prints output successfully.

   void main() {
      int *c1;
      *c1=10;
      printf("%d\n", *c1);
      printf("%d\n", sizeof(c1));
      printf("%d\n", sizeof(*c1));
      printf("%d\n", c1);
      int *c2=c1+1;
      printf("%d\n", c2);
      printf("%d\n",c2-c1);
   }

Can anyone explain the difference? As of understanding, I am assigning the value 10 to the pointer c1 holding address, trying to print the value at c1. So In both it should throw segv error. someone please clarify me

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 3
    `c1` is *uninitialised* so you must not dereference it. The behaviour is undefined. Aside: use `%zu` for the sizeof, use `%p` for the pointer value. Take notice of all compiler warnings. – Weather Vane Aug 19 '21 at 09:18
  • https://www.tutorialspoint.com/cprogramming/c_pointers.htm check this. – gregni Aug 19 '21 at 09:23
  • Both programs use the uninitialized pointer `c1` which triggers undefined behaviour. You try to assign 1' to the memory address contained in `c1` but you never put any valid memory address into `c1` , instead `c1` contains an undetermined value – Jabberwocky Aug 19 '21 at 09:33
  • 1
    @gregni Tutorialspoint is a generally bad source and I wouldn't recommend it. As an example, in the very page you linked, `%x` is being used to print a pointer address when `%p` should be used instead. – mediocrevegetable1 Aug 19 '21 at 09:36
  • 1
    I would recommend learning C first, before just doing random stuff. – Cheatah Aug 19 '21 at 09:42

1 Answers1

3

The pointer c1 is not initialized and has indeterminate value.

int *c1;

So dereferencing the pointer

*c1=10;

results in undefined behavior.

Also you may not apply the subtract operation for pointers that do not point to elements of the same array as you are doing

c2-c1

Pay attention to that the value returned by the operator sizeof has the type size_t. It means that you need to use the conversion specifier zu instead of d in calls of printf

printf("%zu\n", sizeof(c1));

To output a pointer you need to use the conversion specifier p instead of d

printf("%p\n", ( void * )c1);

And according to the C Standard the function main without parameters shall eb declared like

int main( void )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335