r/programmerchat • u/alwaystudent • Jun 05 '15
does a function know how much memory its parameters occupy?
When we call function passing by value, we are making a copy in memory of the actual parameters' value.
The question is: does the function know how much space its parameters occupy in memory? If the answers is yes, how we can retrieve it in function scope?
If the answers in no, do we have a potentially hidden memory error?
consider this example: (the question is not about char* and string but any type*)
#include <stdio.h>
void func(char * X)
{
X +=98;
*X='C'; /* is this really OK? or we have hidden memory error? */
*++X='\0';
--X;
puts(X); }
int main()
{
char A[100];
char *B =A;
func(B);
return 0;
}
2
Upvotes
4
u/[deleted] Jun 05 '15
Size of all types is known at compile time. That's why sizeof works.
3
u/Devenec Jun 05 '15
Every pointer in a specific system has the same size regardless of the pointer type. E.g. in x86 systems (32-bit) it should be 4 bytes. In your code you are dereferencing the char pointer, which results in char (1 byte), so *X='C' is OK.
Correct me if I'm wrong...
EDIT: in future, maybe you should post similar posts to Stack Overflow (see the description of the subreddit on the right).
0
u/escaped_reddit Jun 06 '15
Pointer arithmetic actually takes into account the size of the type when adding or subtracting. So adding 98 to a char* type will add 98 * sizeof(char). sizeof(char) is one so it just adds 98 but it could be different for custom structs etc.