-2

I am using Ubuntu and gcc for compilation.

#include<stdio.h>
void main()
{
  char *c =0 ;
  while(1)
   {
     printf("%p",c);
     c++;
    // printf("%c",*c); // behavior after un-commenting this line is strange.
   }
}

When I execute this code, it start printing large number of addresses which is perfectly fine. But when I un-comment printf("%c",*c) , The code don't even print first address and produce segmentation fault. I know what segmentation fault is and I intentionally wrote this code But I was expecting it would print few addresses (at-least the first address) before segmentation fault but it simply terminates without printing anything

Akash Mahajan
  • 512
  • 4
  • 16

2 Answers2

3

Undefined Behavior

  1. You seem to be aware that the code you've written is broken because of the dereference.
  2. You don't seem to be aware that %p expects a void pointer. So make sure you cast c to that.

Line Buffering

Most consoles will line buffer the output. So try using:

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

or explicitly flush the output with

fflush(stdout);
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Shouldn't the answer be `printf("%p\n",(void *)c);` ? – Gopi Jan 12 '15 at 17:34
  • Brilliant suggestion. It worked. That exactly what I was looking for Thanks for the answer but it would be very helpful if you can enlighten me why fflush(stdout) worked. – Akash Mahajan Jan 12 '15 at 17:36
  • 1
    @AkashMahajan: Your console realizes that actually printing things to the screen is expensive. So it waits until either its internal buffer is full, it sees a newline, or it is explicitly told to write things to the screen. – Bill Lynch Jan 12 '15 at 17:37
0

Incrementing a pointer that points to NULL invokes undefined behavior.

C11: 6.5.6 Additive operators (p8):

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

Since c is not pointing to an array.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264