I am using a function to parse through userID, and paswd and some error checking. The function is called from my main()... However when executed only the first 4 characters of my UserID and Pswd are successfully extracted. I am new to C-programming and coming from C# I am not sure where I am going wrong. This should be fairly easy, can someone point me in the right direction?
static void func1(int argc, char *argv[], char *UserID[30], char *Psw[30])
{
strncpy(UserID, argv[1], sizeof(UserID));
strncpy(Psw, argv[2], sizeof(Psw));
}
int main(int argc, char *argv[])
{
char UserID[30];
char Psw[30];
func1(argc, argv, UserID, Psw);
}
Also, just to point out, if I don't use the external function, and have all the code in my main func then it works.
EDIT:-
Figured out the issue:-
static void func1(int argc, char *argv[], char *UserID, char *Psw)
{
strncpy(UserID, argv[1], UserIDMaxSize);
strncpy(Psw, argv[2], PswMaxSize);
}
int main(int argc, char *argv[])
{
char UserID[UserIDMaxSize + 1]; /* max val defined in a header file */
char Psw[PswMaxSize + 1]; /* max val defined in a header file */
func1(argc, argv, UserID, Psw);
}
sizeof doesnt work quite as I expected it to.. it was reading the size of my pointer which is always 4 chars by default.
strcpy()orstrncpy(). While the later is often labeled as "safe", its use still has two major pitfalls: 1. it requires an upper limit on the length of the string, and 2. it may trigger buffer overruns due to missing termination. Use allocating functions likegetline(),strdup(), andasprintf()instead.