Let's say I have a C function:
Func(void* param);
Is there a way to know number of bytes of param content?
Let's say I have a C function:
Func(void* param);
Is there a way to know number of bytes of param content?
No, it is not possible. That's why almost all functions that takes pointers as arguments has an extra argument for size. It should be like this:
void func(void *param, int size);
Also note that it is up to the function to interpret the size
argument. It can be number of bytes, number of elements or whatever.
The important thing here to remember is the only thing param
is, is a memory address. Nothing more, nothing less.
Some functions doesn't utilize this. One example is strcpy(char * dest, char * src)
that copies a string, but this function assumes two things. It assumes that src
is a zero-terminated string. strcpy
will read from src
until it hits a '\0'
character. Furthermore, it assumes that dest
points at a memory location big enough to hold the string.
sizeof(*param)
will not work. param
is only a pointer to where the memory chunk starts. It would be the same as using sizeof(void)
For starters the type void
is an incomplete type that is its size in bytes is indeterminate.
From the C Standard (6.2.5 Types)
19 The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.
However if you have a pointer of some other type as an argument of a function as for example
T *param
then in general case you again will be unable to determine the number of bytes occupied by the referenced actual data.
Pointers do not keep information whether they point to a single object or the first object of an array.
For example if you have a function declared like this
void f( const char *s );
then it can be called for example for these objects of different types
char c = 'A';
f( &c );
and
char s[] = "Hello";
f( s );
Of course you can get the number of bytes occupied by the element of an array or a single object referenced to by pointer as for example using expression
sizeof( *param )
But in case of the type void *
you may not do even this though some compilers have their own language extensions that allow to apply the operator sizeof
for the type void. In this case the returned value of the expression is usually equal to 1.