Pointer and memory arithmetic in C - c

Taking the following program:
#include <stdio.h>
#include <stddef.h>
int main(void) {
int *a = &(int) {4};
ptrdiff_t b = (a+1) - a;
int c = (char*) (a+1) - (char*) a; // actual memory difference
printf("The first memory address is at: %p and the one after is: %p\n"
"The difference with pointer arithmetic is: %td\n"
"And actual difference in memory address is: %d\n",
a, a+1, b, c);
}
The first memory address is at: 0x7fff9cb3a1e0 and the one after is: 0x7fff9cb3a1e4
The difference with pointer arithmetic is: 1
And actual difference in memory address is: 4
Is this the proper way to do:
ptr arithmetic: ptrdiff_t b = (a+1) - a;
actual arithmetic between memory addresses: (char*) (a+1) - (char*) a;
Formatters: %td for ptrdiff_t, and %d for actual memory difference (wouldn't this just be an int or is there a better formatter for this?)

In
int *a = &(int) {4};
{4} is a compound literal, its address can be taken just as you did.
ptrdiff_t b = (a+1) - a;
Pointer subtraction is well defined when the pointers involved point to elements of the same array, or the element past the last. Pointer a can point to an object or an array of objects. An object and array are different types, but a pointer doesn't distinguish the two, so that a scalar is treated as an array of 1 element. This code is well defined.
In
int c = (char*) (a+1) - (char*) a;
the type of difference is ptrdiff_t, which is int only on a 32-bit architecture.

Anytime you take the difference of two pointers, the result has type ptrdiff_t.
So both b and c should be of this type, and %td is the format specifier you would use to print it.
Also, the %p format specifier expects a void * as a argument. And since the implicit conversion to/from void * can't happens with variadic parameters, this is one of the few times an explicit cast to void * is required.

Related

Simple implementation of sizeof in C

I came across one simple (maybe over simplified) implementation of the sizeof operator in C, which goes as follows:
#include <stdio.h>
#define mySizeof(type) ((char*)(&type + 1) - (char*)(&type))
int main() {
char x;
int y;
double z;
printf("mySizeof(char) is : %ld\n", mySizeof(x));
printf("mySizeof(int) is : %ld\n", mySizeof(y));
printf("mySizeof(double) is : %ld\n", mySizeof(z));
}
Note: Please ignore whether this simple function can work in all cases; that's not the purpose of this post (though it works for the three cases defined in the program).
My question is: How does it work? (Especially the char* casting part.)
I did some investigations as follows:
#include <stdio.h>
#define Address(x) (&x)
#define NextAddress(x) (&x + 1)
int main() {
int n = 1;
printf("address is : %lld\n", Address(n));
printf("next address is : %lld\n", NextAddress(n));
printf("size is %lld\n", NextAddress(n) - Address(n));
return 0;
}
The above sample program outputs:
address is : 140721498241924
next address is : 140721498241928
size is 1
I can see the addresses of &x and &x + 1. Notice that the difference is 4, which means 4 bytes, since the variable is int type. But, when I do the subtraction operation, the result is 1.
What you have to remember here is that pointer arithmetic is performed in units of the size of the pointed-to type.
So, if p is a pointer to the first element of an int array, then *p refers to that first element and the result of the p + 1 operation will be the address resulting from adding the size of an int to the address in p; thus, *(p + 1) will refer to the second element of the array, as it should.
In your mySizeof macro, the &type + 1 expression will yield the result of adding the size of the relevant type to the address of type; so, in order for the subsequent subtraction of &type to yield the size in bytes, we cast the pointers to char*, so that the subtraction will be performed in base units of the size of a char … which is guaranteed by the C Standard to be 1 byte.
Pointers carry the information about their type. If you have a pointer to a 4-byte value such is int, and add 1 to it, you get a pointer to the next int, not a pointer to the second byte of the original int. Similarly for subtraction.
If you want to obtain the item size in bytes, it's necessary to force pointers to point to byte-like items. Hence the typecast to char*.
See also Pointer Arithmetic
Your implementation of sizeof works for most objects, albeit you should modify it this way:
the misnamed macro argument type (which cannot be a type) should be bracketed in the expansion to avoid operator precedence issues.
the expression has type ptrdiff_t, it should be cast as size_t
the printf format for size_t is %zu. Note that %ld is incorrect for ptrdiff_t, you should use %td for this.
Here is a modified version:
#include <stdio.h>
#define mySizeof(obj) ((size_t)((char *)(&(obj) + 1) - (char *)&(obj)))
int main() {
char x;
int y;
double z;
printf("mySizeof(char) is : %zu\n", mySizeof(x));
printf("mySizeof(int) is : %zu\n", mySizeof(y));
printf("mySizeof(double) is : %zu\n", mySizeof(z));
return 0;
}
How it works:
valid pointers can point to an element of an array or the the element just past the last element of the array. Objects that are not arrays are considered as arrays of 1 element for this purpose.
so if obj is a valid lvalue &(obj) + 1 is a valid pointer past the end of obj in memory and casting it as (char *) is valid.
similarly (char *)&(obj) is a valid pointer to the beginning of the object, and the only iffy operation here is the subtraction of 2 valid pointers that cannot be considered to point to the same array of char.
the C standard make a special case of character type pointers to allow the representation of objects to be accessed as individual bytes. So (char *)(&(obj) + 1) - (char *)&(obj) effectively evaluates to the number of bytes in the representation of obj.
Note these limitations for this implementation of sizeof:
it does not work for types as in mySizeof(int)
the argument must be an object: mySizeof(1) does not work, nor mySizeof(x + 1)
the object may be struct or an array: char foo[3]; mySizeof(foo) but not a string literal: mySizeof("abc") nor a compound literal: mySizeof((char[2]){'a','b'})

Subtracting two pointers giving unexpected result

#include <stdio.h>
int main() {
int *p = 100;
int *q = 92;
printf("%d\n", p - q); //prints 2
}
Shouldn't the output of above program be 8?
Instead I get 2.
Undefined behavior aside, this is the behavior that you get with pointer arithmetic: when it is legal to subtract pointers, their difference represents the number of data items between the pointers. In case of int which on your system uses four bytes per int, the difference between pointers that are eight-bytes apart is (8 / 4), which works out to 2.
Here is a version that has no undefined behavior:
int data[10];
int *p = &data[2];
int *q = &data[0];
// The difference between two pointers computed as pointer difference
ptrdiff_t pdiff = p - q;
intptr_t ip = (intptr_t)((void*)p);
intptr_t iq = (intptr_t)((void*)q);
// The difference between two pointers computed as integer difference
int idiff = ip - iq;
printf("%td %d\n", pdiff, idiff);
Demo.
This
int *p = 100;
int *q = 92;
is already invalid C. In C you cannot initialize pointers with arbitrary integer values. There's no implicit integer-to-pointer conversion in the language, aside from conversion from null-pointer constant 0. If you need to force a specific integer value into a pointer for some reason, you have to use an explicit cast (e.g. int *p = (int *) 100;).
Even if your code somehow compiles, its behavior in not defined by C language, which means that there's no "should be" answer here.
Your code is undefined behavior.
You cannot simply subtract two "arbitrary" pointers. Quoting C11, chapter §6.5.6/P9
When two pointers are subtracted, both shall point to elements of the same array object,
or one past the last element of the array object; the result is the difference of the
subscripts of the two array elements. The size of the result is implementation-defined,
and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. [....]
Also, as mentioned above, if you correctly subtract two pointers, the result would be of type ptrdiff_t and you should use %td to print the result.
That being said, the initialization
int *p = 100;
looks quite wrong itself !! To clarify, it does not store a value of 100 to the memory location pointed by (question: where does it point to?) p. It attempts to sets the pointer variable itself with an integer value of 100 which seems to be a constraint violation in itself.
According to the standard (N1570)
When two pointers are subtracted, both shall point to elements of
the same array object, or one past the last element of the array
object; the result is the difference of the subscripts of the two
array elements.
These are integer pointers, sizeof(int) is 4. Pointer arithmetic is done in units of the size of the thing pointed to. Therefore the "raw" difference in bytes is divided by 4. Also, the result is a ptrdiff_t so %d is unlikely to cut it.
But please note, what you are doing is technically undefined behaviour as Sourav points out. It works in the most common environments almost by accident. However, if p and q point into the same array, the behaviour is defined.
int a[100];
int *p = a + 23;
int *q = a + 25;
printf("0x%" PRIXPTR "\n", (uintptr_t)a); // some number
printf("0x%" PRIXPTR "\n", (uintptr_t)p); // some number + 92
printf("0x%" PRIXPTR "\n", (uintptr_t)q); // some number + 100
printf("%ld\n", q - p); // 2

Distance between arbitrary pointers

I am trying to print the distance between two pointers, but I have found that sometimes the code doesn't work well.
#include <stdio.h>
#include <math.h>
/**
* Print the distance between 2 pointers
*/
void distance(int * a0, int * a1){
size_t difference = (size_t) a1 - (size_t) a0;
printf("distance between %p & %p: %u\n" ,a0, a1, abs((int) difference));
}
Trying this works perfectly!!
int main(void){
int x = 100;
int y = 3000;
distance(&x, &y);
return 0;
}
printing (example):
distance between 0028ff18 & 0028ff14: 4
But start to going wrong with this code
int main(void){
int x = 100;
int p = 1500;
int y = 3000;
distance(&x, &y);
p = p + 2; // remove unused warning
// &p
return 0;
}
printing (example):
distance between 0028ff18 & 0028ff14: 4
When it has to print 8 because of an integer separating this values!
But if I uncomment //&p, it works again.
It is as if the variable p does not exist until its memory address is used.
I'm using gcc 4.9.3 on windows 7 (64 bits)
p is not used in your program and is likely to be optimized out. Anyway this is implementation details and the compiler is free to even change the order of the x and y objects in memory.
it is as if the variable p not exist until its memory address is used
gcc will optimize away any variables that do not affect the behavior of the program.
Secondly, you cannot assume that variables are laid out in any particular order in memory, and the "distance" between any two may be completely meaningless. The only time you can rely on the distance between two pointers to have any meaning is when they are both pointing to elements within the same array object.
Pointer arithmetic is valid only between pointers to elements of the same array, or one past the end. Going against that will have unpredictable and implementation-defined results. In this case, it seems you have found the answer yourself: gcc is optimizing p away, but in any case, you can't assume any specific order of variables in memory, yet alone do pointer arithmetic.
Also, this:
size_t difference = (size_t) a1 - (size_t) a0;
Should be:
ptrdiff_t difference = a1 - a0;
The correct type for the difference between two pointers is ptrdiff_t (defined in stddef.h). You shouldn't cast the pointers to size_t because pointer values are not necessarily representable in a size_t (if you want a numeric type to convert pointers to, use uintptr_t or intptr_t).
The %p format specifier expects a void *, so you should cast the pointers, and the correct format specifier for ptrdiff_t is %td:
printf("distance between %p & %p: %td\n", (void *) a0, (void *) a1, difference);

typecasting a pointer to an int .

I can't understand the output of this program .
What I get of it is , that , first of all , the pointers p, q ,r ,s were pointing towards null .
Then , there has been a typecasting . But how the heck , did the output come as 1 4 4 8 . I might be very wrong in my thoughts . So , please correct me if I am wrong .
int main()
{
int a, b, c, d;
char* p = (char*)0;
int *q = (int *)0;
float* r = (float*)0;
double* s = (double*)0;
a = (int)(p + 1);
b = (int)(q + 1);
c = (int)(r + 1);
d = (int)(s + 1);
printf("%d %d %d %d\n", a, b, c, d);
_getch();
return 0;
}
Pointer arithmetic, in this case adding an integer value to a pointer value, advances the pointer value in units of the type it points to. If you have a pointer to an 8-byte type, adding 1 to that pointer will advance the pointer by 8 bytes.
Pointer arithmetic is valid only if both the original pointer and the result of the addition point to elements of the same array object, or just past the end of it.
The way the C standard describes this is (N1570 6.5.6 paragraph 8):
When an expression that has integer type is added to or subtracted
from a pointer, the result has the type of the pointer operand. If the
pointer operand points to an element of an array object, and the array
is large enough, the result points to an element offset from the
original element such that the difference of the subscripts of the
resulting and original array elements equals the integer expression.
[...]
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. If the result points one past the last element of the
array object, it shall not be used as the operand of a unary *
operator that is evaluated.
A pointer just past the end of an array is valid, but you can't dereference it. A single non-array object is treated as a 1-element array.
Your program has undefined behavior. You add 1 to a null pointer. Since the null pointer doesn't point to any object, pointer arithmetic on it is undefined.
But compilers aren't required to detect undefined behavior, and your program will probably treat a null pointer just like any valid pointer value, and perform arithmetic on it in the same way. So if the null pointer points to address 0 (this is not guaranteed, BTW, but it's very common), then adding 1 to it will probably give you a pointer to address N, where N is the size in bytes of the type it points to.
You then convert the resulting pointer to int (which is at best implementation-defined, will lose information if pointers are bigger than int, and may yield a trap representation) and you print the int value. The result, on most systems, will probably show you the sizes of char, int, float, and double, which are commonly 1, 4, 4, and 8 bytes, respectively.
Your program's behavior is undefined, but the way it actually behaves on your system is typical and unsurprising.
Here's a program that doesn't have undefined behavior that illustrates the same point:
#include <stdio.h>
int main(void) {
char c;
int i;
float f;
double d;
char *p = &c;
int *q = &i;
float *r = &f;
double *s = &d;
printf("char: %p --> %p\n", (void*)p, (void*)(p + 1));
printf("int: %p --> %p\n", (void*)q, (void*)(q + 1));
printf("float: %p --> %p\n", (void*)r, (void*)(r + 1));
printf("double: %p --> %p\n", (void*)s, (void*)(s + 1));
return 0;
}
and the output on my system:
char: 0x7fffa67dc84f --> 0x7fffa67dc850
int: 0x7fffa67dc850 --> 0x7fffa67dc854
float: 0x7fffa67dc854 --> 0x7fffa67dc858
double: 0x7fffa67dc858 --> 0x7fffa67dc860
The output is not as clear as your program's output, but if you examine the results closely you can see that adding 1 to a char* advances it by 1 byte, an int* or float* by 4 bytes, and a double* by 8 bytes. (Other than char, which by definition has a size of 1 bytes, these may vary on some systems.)
Note that the output of the "%p" format is implementation-defined, and may or may not reflect the kind of arithmetic relationship you might expect. I've worked on systems (Cray vector computers) where incrementing a char* pointer would actually update a byte offset stored in the high-order 3 bits of the 64-bit word. On such a system, the output of my program (and of yours) would be much more difficult to interpret unless you know the low-level details of how the machine and compiler work.
But for most purposes, you don't need to know those low-level details. What's important is that pointer arithmetic works as it's described in the C standard. Knowing how it's done on the bit level can be useful for debugging (that's pretty much what %p is for), but is not necessary to writing correct code.
Adding 1 to a pointer advances the pointer to the next address appropriate for the pointer's type.
When the (null)pointers+1 are recast to int, you are effectively printing the size of each of the types being pointed to by the pointers.
printf("%d %d %d %d\n", sizeof(char), sizeof(int), sizeof(float), sizeof(double) );
does pretty much the same thing. If you want to increment each pointer by only 1 BYTE, you'll need to cast them to (char *) before incrementing them to let the compiler know
Search for information about pointer arithmetic to learn more.
You're typecasting the pointers to primitive datatypes rather type casting them to pointers themselves and then using * (indirection) operator to indirect to that variable value. For instance, (int)(p + 1); means p; a pointer to constant, is first incremented to next address inside memory (0x1), in this case. and than this 0x1 is typecasted to an int. This totally makes sense.
The output you get is related to the size of each of the relevant types. When you do pointer arithmetic as such, it increases the value of the pointer by the added value times the base type size. This occurs to facilitate proper array access.
Because the size of char, int, float, and double are 1, 4, 4, and 8 respectively on your machine, those are reflected when you add 1 to each of the associated pointers.
Edit:
Removed the alternate code which I thought did not exhibit undefined behavior, which in fact did.

Some pointer questions [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is array name a pointer in C?
I was running the following code
#include <stdio.h>
int main()
{
int a[4] = {1,2,3,4};
int (*b)[4] = &a;
int k = sizeof(a);
printf("\n\n%d\n\n", k);
printf("a = %u, b = %u, *b = %u, data = %d", a, b, *b, **b);
return 0;
}
I got the following output
a = 3485401628, b = 3485401628, *b = 3485401628, data = 1
Here I am assigning the address of a to b, as the type of b is int**, but in the output I am getting that the address pointed by the a is the same as the address pointed by b.
It seems little confusing to me. What is the explanation?
The value of array a is the pointer to the first element of the array a.
The value of pointer &a (which is the same value and type as pointer b) is the pointer to the array a.
They have the same value (but different types) as they both start at the same memory address. There is no padding possible at the beginning of an array.
When evaluated a is of type int * and &a is of type int (*)[4].
Note that the correct way to print the address of a pointer is to use conversion specifier p. E.g.,
/* And p requires the argument to be a void *, so use a cast if
* it is not the case
*/
printf("%p %p\n", (void *) a, (void *) &a);
On expressions (such as an argument for printf) arrays are decayed to pointers (to their respective arrays), meaning that if "b" points to "a", on an expression, "a" will also be a pointer to "a" (the block of memory allocated for "a").
The way of accessing elements at runtime however (internally), is different. In this case, "b" would require an additional indirection.

Resources