I am studying pointers and found I get incorrect size of a pointer.
What I learned is that since p_num is a pointer to an int, it should show 4 bytes but is shows 8.
What could the possible reason for it?
#include <stdio.h>
int main()
{
int num = 0;
int * p_num = NULL;
num = 10;
printf("num address: %p\n", &num);
printf("num size: %zd\n", sizeof(num));
printf("num value: %d\n\n", num);
p_num = #
printf("p_num address: %p\n", (void*)&p_num);
printf("p_num size: %zd\n", sizeof(p_num));
printf("p_num value: %p\n", p_num);
printf("p_num value pointed: %d\n", *p_num);
return 0;
}
Output:
num address: 0x7fffcb0e8ffc
num size: 4
num value: 10
p_num address: 0x7fffcb0e8ff0
p_num size: 8
p_num value: 0x7fffcb0e8ffc
p_num value pointed: 10
What could the possible reason for it?
The size of a pointer is dependent upon the architecture. On 32-bit architectures, a pointer usually occupies 4 byte in memory, on 64-bit architectures commonly 8 byte.
So there is nothing wrong with the program or your system itself, if you use a 64-bit architecture as you said in the comments. You just had an incorrect assumption of:
What I learned is that ... a pointer to an int ... should show 4 bytes.
Furthermore, this is usually valid for all pointer types, not only pointers to int. They usually have the same size in memory, but the standard does not require that as you can see in the quote from ISO/IEC 9899:2011 (C11) in this answer regarding to the exact question for that.
The size of a pointer may be also different from the size of the object the pointer point to. So differ between the size of a pointer object and the size of an object the pointer point to.
What I learned is that since p_num is a pointer to an int, it should show 4 bytes but is shows 8.
Your assumption is incorrect.
The int is one variable.
The int pointer is another variable.
So two different variables and these two variables do not need to have the same size.
In other words:
printf("p_num size: %zu\n", sizeof(p_num)); // Gives you the size of the pointer
printf("p_num size: %zu\n", sizeof(*p_num)); // Gives you the size of the pointed to object
^
notice the *
In your case you see that size of int is 4 while size of int pointer is 8. This is perfectly legal.
Most likely, you could have made the size difference even bigger by looking at a char and a char pointer. Then you would most likely see 1 for char and still 8 for char pointer.
sizeof(p_num) is the size of the pointer, not the size of the thing it points to.
sizeof(*p_num) is the size of the thing it points to.
Also, the parentheses are unnecessary. sizeof p_num and sizeof *p_num work fine. Parentheses are needed only to take the sizes of types (rather than expressions) or of complicated expressions.
In order to address more than 4gb in memory the pointers should be 8 bytes of size. Addresses of Memory more than 4gb cannot be represented using 32 bits i.e. 4 bytes.
In the 64-bit machines, the size of pointer is 8 bytes, because a pointer is a memory address. The pointer p_num pointes to the varibale num that is just one of several integer types. In the 64-bits system, sizeof(int) = 4.
Related
I am using code below and getting different values.
int *p;
printf("Size of *p = %d", sizeof(*p)); // Here value is 4
printf("Size of p = %d", sizeof(p)); // Here value is 8
Can any one please explain, what exactly is the reason behind this?
For any pointer variable p, the variable p itself is the pointer and the size of it is the size of the pointer. *p is what p is pointing to, and the size of *p is the size of what is being pointed to.
So when sizeof(p) reports 8 then you know that a pointer on your system is 8 bytes, and that you're probably on a 64-bit system.
If sizeof(*p) reports 4 then you know that the size of int (which is what p is pointing to in your case) is 4 bytes, which is normal on both 32 and 64 bit systems.
You would get the same result by doing sizeof(int*) and sizeof(int).
Oh and a last note: To print the result of sizeof (which is of type size_t) then you should really use the "z" prefix, and an unsigned type specifier (since size_t is unsigned). For example "%zu". Not doing that is technically undefined behavior.
sizeof(*p) returns size of type what the pointer points to while sizeof(p) returns size of pointer itself.
In your case *p = int and sizeof(int) = 4 on your machine, while you need 8 bytes to store memory address (address where p points to).
sizeof(p) is the size of the pointer itself. It depends on the size of the address bus. Which means for a 64-bit system, the address bus size will be 64-bit (8 bytes) so pointer will be 8 bytes long (that shows your system is 64-bit). And on a 32-bit system, it's size will be 32-bit(4 bytes).
sizeof(*p) is the size of pointer type i.e. int here. So usually int is of 32-bit long that is 4 bytes.
I was reading more about arrays vs pointers in C and wrote the following program.
#include <stdio.h>
int arr[10] = { } ;
typedef int (*type)[10] ;
int main()
{
type val = &arr ;
printf("Size is %lu\n", sizeof(val)) ;
printf("Size of int is %lu\n", sizeof(int)) ;
}
If, I execute this program, then sizeof(val) is given to be 8 and sizeof(int) is given to be 4.
If val is a pointer to the array with 10 elements, shouldn't it's size be 40. Why is the sizeof(val) 8 ?
If val is a pointer to the array...
Yes, it is, and sizeof(val) produces the size for the "pointer to the array", not the array itself.
...shouldn't it's size be 40.?
No, sizeof(val) calculates the size of the operand, the "pointer" here. In your platform, the size of a pointer seems to be 64 bits, i.e., 8 bytes. So, it gives 8.
Also, as I mentioned, use %zu to print size_t, the type produced by sizeof operator.
First of all this initialization of an array
int arr[10] = { } ;
is invalid in C. You may not use emplty braces in C (in C++ they are allowed). You have to write
int arr[10] = { 0 } ;
In C the corresponding initializer is defined the following way
initializer:
{ initializer-list }
{ initializer-list , }
while in C++
braced-init-list:
{ initializer-list ,opt }
{ }
As for this statement
printf("Size is %lu\n", sizeof(val)) ;
then val is a pointer because it has type type defined like
typedef int (*type)[10] ;
Change this statement to
printf( "Size is %zu\n", sizeof( *val ) );
if you want to get the size of the object (that is of the array) pointed to by the pointer.
sizeof returns the size of the pointer itself. In 64bit system it is 8 bytes.
Pointers have no knowledge of the size of buffer they points to.
A pointer is a distinct data type and always has a fixd size. Think of a pointer as a sign that points to the actual data, and the sign always the same size - regardless if it points to a single character or a larger array.
val is pointer and its size is equivalent to address bus size of system.
so, sizeof(val) or sizeof(anyPointer) will give you 8 as output.
if you want 40 then try sizeof(arr).
Pointer to an array is simple pointer where you can write val++ while array name is constant pointer you cannot write arr++.
you can also check this link
Most probably you are in a 64 bit PC where memory address need 64 bits or 8 byte space for representation.
Now the pointer actually holds the memory address, whereas it may hold an address of int or maybe an address of int[], doesn't matter.
So, when you execute,
printf("Size is %lu\n", sizeof(val)) ;
it shows 8 as because the pointer holds address which need 64 bits space.
And
printf("Size of int is %lu\n", sizeof(int)) ;
this line just print the size of int which is 4 bytes.
How can I justify the output of the below C program?
#include <stdio.h>
char *c[] = {"Mahesh", "Ganesh", "999", "333"};
char *a;
char **cp[] = {c+3, c+2, c+1, c};
char ***cpp = cp;
int main(void) {
printf("%d %d %d %d ",sizeof(a),sizeof(c),sizeof(cp),sizeof(cpp));
return 0;
}
Prints
4 16 16 4
Why?
Here is the ideone link if you want to fiddle with it.
char *c[] = {"Mahesh", "Ganesh", "999", "333"};
c is an array of char* pointers. The initializer gives it a length of 4 elements, so it's of type char *[4]. The size of that type, and therefore of c, is 4 * sizeof (char*).
char *a;
a is a pointer of type char*.
char **cp[] = {c+3, c+2, c+1, c};
cp is an array of char** pointers. The initializer has 4 elements, so it's of type char **[4]. It size is 4 * sizeof (char**).
char ***cpp = cp;
cpp is a pointer to pointer to pointer to char, or char***. Its size is sizeof (char***).
Your code uses %d to print the size values. This is incorrect -- but it happens to work on your system. Probably int and size_t are the same size. To print a size_t value correctly, use %zu -- or, if the value isn't very large, you can cast it to int and use %d. (The %zu format was introduced in C99; there might still be some implementations that don't support it.)
The particular sizes you get:
sizeof a == 4
sizeof c == 16
sizeof cp == 16
sizeof cpp == 4
are specific to your system. Apparently your system uses 4-byte pointers. Other systems may have pointers of different sizes; 8 bytes is common. Almost all systems use the same size for all pointer types, but that's not guaranteed; it's possible, for example, for char* to be larger than char***. (Some systems might require more information to specify a byte location in memory than a word location.)
(You'll note that I omitted the parentheses on the sizeof expressions. That's legal because sizeof is an operator, not a function; its operand is either an expression (which may or may not be parenthesized) or a type name in parentheses, like sizeof (char*).)
a is an usually pointer, which represents the memory address. On 32-bit operating system, 32bit (4 Byte) unsigned integer is used to represent the address. Therefore, sizeof(a) is 4.
c is an array with 4 element, each element is a pointer, its size is 4*4 = 16
cp is also an array, each element is a pointer (the first *, wich point to another pointer (the second *). The later pointer points to an string in the memory. Therefore its basic element size should represent the size of a pointer. and then sizeof(cp) = 4*4 = 16.
cpp is a pointer's pointer's pointer. It is as well represent the 32bit memory address. therefore its sizeof is also 4.
a is a pointer. cpp is also a pointer just to different type (pointer to pointer to pointer).
Now c is an array. You have 4 elements, each is a pointer so you have 4 * 4 = 16 (it would be different if you would run it on x64).
Similar goes for cp. Try changing type to int and you will see the difference.
So the reason you got 4 16 16 4, is because 'a' is simply a pointer, on its own, which only requires 4 bytes (as a pointer is holding a 32bit address depending on your architecture) and so when you have a **pointer which is == to a *pointer[], your really making an array of pointers, and since you initalized 4 things that created 4 pointers, thus the 4x4 = 16. And for the cpp you may ask "well wouldn't it then be 16 as it was initalized?" and the answer is no, because a ***pointer is its own separate variable and still just a pointer(a pointer to a pointer to a pointer, or a pointer to an array of pointers), and requires only 4bytes of memory.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
p = (int *)malloc(20);
printf("%d\n", sizeof(p));
free(p);
return 0;
}
On my 64-bit machine, 4 is printed as the size of p. I'm assuming this is because integers take up 4 bytes in memory, and p is an integer pointer. What if I was running a 32-bit machine? Also, what would happen if I replaced
int *p with double *p
and
(int *)malloc(20) with (double *)malloc(20)?
You are assuming wrong.
In printf("%d\n", sizeof(p)); you are not printing size of integer.You are printing here sizeof 'pointer to an integer' which is 4 bytes in your case.Most probably you will get same result on 32-bit machine.
Now about malloc, It allocates number of bytes and returns pointer to it.So same size of memory will be allocated even if you cast the pointer from int* to double*.
In pointers, It will take four bytes for all pointers.
So while you are checking with sizeof, even it is a character pointer it will give four bytes. If you need the value of that pointer use like this.
printf("%d\n", sizeof(p));// It will give the pointer size.
malloc is allocating the given bytes. And it will give equal to all the pointers. Then don't cast the result of malloc. Refer this link.
You have some misunderstanding let me point them,
p = (int *)malloc(20);
You are allocating memory of 20 bytes and malloc returns a void pointer and but compiler does the casting for you and (int *) is not needed. Even though you have a pointer to a double or an int it takes the same amount of bytes (In a 32bit system this merely for mapping 4GB memory space).
// Should this be 4 or 8?
printf("%d\n", sizeof(p));
This should be 8 on a x64 platform if your executable or the build is x64 only. I assume your build is 32bit and it returns 4.
Above printf has a wrong specifier. sizeof returns size_t and not an int. So correct form should be,
printf("%zu\n", sizeof(p));
Irrespective of whether 64-bit system or 32-bit system, size of a pointer variable is 4 bytes by default since 64-bit build settings also have Debug32 by default.
If we specifically change build settings on 64-bit, then the pointer variable can hold 8 bytes.
I'm assuming this is because integers take up 4 bytes in memory, and p is an integer pointer.
Your assumption is not correct ! To answer your doubt not only integer pointer take up 4 bytes.
int *ptrint;
char *ptrchar;
float *ptrfloat;
double *ptrdouble;
Here all ptrint, ptrchar, ptrfloat, ptrdouble takes 4 bytes of memory since it would be the address stored in that variable.
And if you replace int *p with double *p and (int *)malloc(20) with (double *)malloc(20) , the size would be still 4 bytes. I hope this ans cleared your doubts.
I'm experiencing a problem. I'm trying to get the number of elements in an int array, without passing any explicit parameter, just the pointer to the int array. Now my curiosity:
int * set;
printf("-- %d --", sizeof(set)); //4
set=(int *) malloc(n*sizeof(int));
printf("-- %d --", sizeof(set)); //4
Why are the values the same since before the malloc it isn't initialized and after it is. Thanks
UPDATE:
Is there any way to get the length of an int array?
Because sizeof is evaluated at compile time and yields the size of the type of set, a pointer to int.
There is no generic way to measure the size of memory pointed to by a pointer in C, other than the special case that strings are null terminated by convention.
sizeof will yield the size of the pointer (4 bytes on a 32-bit system, 8 bytes on a 64-bit system), not of the memory pointed to.
If you want to track the size of memory allocated, options are:
Track it in a separate variable
Introduce a special array terminator (for example, the minimum or maximum value of int if your application will never validly use that value.
Use an alternate memory management library (for dmalloc has dmalloc_examine, which will return the size of memory pointed to). These should drop right in with minimal or no code changes, except for where you want to use their expanded memory API.
The item you're measuring, set, is a pointer-to-integer ( int* ).
And a pointer-to-integer is 4-bytes.
sizeof does NOT measure the amount of memory allocated to the pointer.
It only measures the "item" itself (in this case, a pointer).
A pointer is 32 bits or 64 bits.
Meaning 4 or 8 bytes.
int * set;
printf("-- %d --", sizeof(set)); //4
set=(int *) malloc(n*sizeof(int));
printf("-- %d --", n*sizeof(int)); //n*sizeof(int) is the size of your malloc'd memory
hope that helps. in your last statement you were still asking the size of the individual integer pointer which was 4 bytes on your machine. to get the size of your malloced area of memory you need to use the same expression as is inside the malloc function.
and an integer pointer isn't necessarily the same size as an int itself as Mat corrected me on