Tuesday, March 2, 2010

SCANF_S its use....

Hi all,
     while i was coding for a program on Visual studio 2008 , ijust came across a warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
                    Basically scanf_s is more secure. C does no type checking for you, so when you use scanf, C doesn't make sure that what the user inputs will fit in the variable that you've designated. For example, if you use this code,

char name[10]; //declares an array that can hold 10 characters
scanf("%s", name); //gets a string from the user and puts it in name

this will work fine if the user's name is  something smaller than 9 characters (9 because the last character is a terminator), but if the user's name is 10 or more characters, scanf starts writing into memory that doesn't belong to name. C won't catch this or warn you, so you won't find out until something else tries to use that memory and your program crashes.

Because this is such a common issue, scanf_s checks that the user input will fit in the given memory space, so many problems are avoided.


hence using scanf_s(); is a better way to be used


NOTE:WHILE CODING TRY TO SOLVE ALL THE WARNINGS FOR BETTER PRACTICES...

Monday, March 1, 2010

sizeof() Compile time operator

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 itbut 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 functionbut 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 its 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
Avinash