Hi all,
I am just sharing a small Info on C Trap which I came across yesterday……may be most of u will be familiar with it…but I am jus explaining my experience…
Scenario:
Char *ptr = (char*)malloc(sizeof(char)*30);
MyFunc(ptr);
Void MyFunc(char *ptr)
{
Int I = sizeof(ptr); gave me 4 bytes(as ptr is a pointer I mean its storing the address);;;I expected to return entire size allocated USING MALLOC.
I=sizeof(*ptr) ; gave me 1byte(as the value stored in the address pointed by ptr was char type)
}
So here ez my list of learnings;
Actually I used sizeof(ptr); to get the entire memory allocated in main function…but It couldnot be done as sizeof() operator is a compile time operator,and the memory was allocated during runtime.
But after browsing thru net and asking few experienced guys I came to know that it’s the c Limitation in using memory and few latest compilers use some extra memory to keep track of size,datatype,and startpointer..
That is the reason why memset,memcpy fgets will use a 3rd parmemter to store the size of the destination string……
Happycoding
No comments:
Post a Comment