Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming passing a char array into a function

Tags:

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.

like image 457
Philo Avatar asked Apr 11 '16 20:04

Philo


2 Answers

I guess your pointer has a size of 4 Byte. therefore you only read 4 chars.

like image 192
rommon Avatar answered Sep 28 '22 02:09

rommon


Pass the array size to the function

static void func1(int argc, char *argv[], char *UserID, size_t UserIDSize, 
    char *Psw, size_t PswSize)
{
   if (argc> 1) strncpy(UserID, argv[1], UserIDSize);  
   if (argc> 2) strncpy(Psw, argv[2], PswSize);  
} 

int main(int argc, char *argv[])
{
   char UserID[30] = {0};     
   char Psw[30] = {0};
   func1(argc, argv, UserID, sizeof UserID, Psw, sizeof Psw);
}

To insure the destination arrays are null character terminated, suggest strncat() --> "A terminating null character is always appended to the result." strncpy() has too many problems, it does not always result in an array with a null character.

static void func1(int argc, char *argv[], char *UserID, size_t UserIDSize, 
    char *Psw, size_t PswSize) {
   UserId[0] = '\0';
   // if (argc> 1) strncat(UserID, argv[1], UserIDSize);  
   if (argc> 1) strncat(UserID, argv[1], UserIDSize - 1);  
   Psw[0] = '\0';
   // if (argc> 2) strncat(Psw, argv[2], PswSize);  
   if (argc> 2) strncat(Psw, argv[2], PswSize - 1);  
} 

[Edit]

Corrected code - off by 1

like image 42
chux - Reinstate Monica Avatar answered Sep 28 '22 04:09

chux - Reinstate Monica