Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting negative address in c

#include <stdio.h>
int main(void) {
    int a[5] = {0, 1, 2, 3, 4}, *p;
    p = a;
    printf("%d\n%d\n%d\n%d\n%d\n", p, *p);
    return 0;
}

When I executed this code, I got a negative value for p. I have studied that address cannot be negative. Then why I have got a negative value

like image 711
rohit15079 Avatar asked Feb 15 '26 13:02

rohit15079


1 Answers

  1. %d is not the correct format specifier to handle a pointer (address). You should be using %p and cast the corresponding argument to void* for printing an address. Using wrong argument type for a particular format specifier invokes undefined behavior.

    To quote C11 chapter §7.21.6.1

    [...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

  2. In this code, *p does not denote an address, anyway.

  3. You cannot print an array by just using the %ds in a single format string. You need to have a loop. In your code,

    printf("%d\n%d\n%d\n%d\n%d\n", p, *p);
    

    the format string expects 5 ints as argument, while you supply only a pointer and an int. FWIW, supplying insufficient argument for supplied conversion specifiers invoke undefined behavior, too. Quoting the same standard,

    [...] If there are insufficient arguments for the format, the behavior is undefined. [...]

To elaborate, replace

 printf("%d\n%d\n%d\n%d\n%d\n", p, *p);

by

 for (i= 0; i < 5; i++, p++)
 printf("%d %p\n", *p, (void *)p);
like image 137
Sourav Ghosh Avatar answered Feb 17 '26 02:02

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!