S
somenath
Hi All,
I was going through one piece of code which is written by an
experience programmer and it is working fine.
But I think the use of "strstr" is not proper because it may show
undefined behavior.
char *returnValueFromIniFile(char *iniFilePath,char *keyIntheFile)
{
FILE *FD_IniFileP =NULL;
char key[SIZE_OF_ARRAY]={'0'};
static char value[SIZE_OF_ARRAY]={'\0'};
FD_IniFileP = fopen(iniFilePath,"r");
if( FD_IniFileP != NULL )
{
/* File Open Success*/
while (fscanf(FD_IniFileP,"%s",key)!= EOF)
{
if(strstr(key,keyIntheFile)!=NULL)
{
/*Make sure key contains "="*/
if(strstr(key,"=")!=NULL)
{
/*Sepereate the key and the value */
char *positionOfequal = strstr(key,"="); /* as "="
is not terminated by '\0' it can show undefined behavior ? */
/*increment the positionOfequal to reach the
beganing of the value */
positionOfequal +=1;
assert(strlen(positionOfequal)<SIZE_OF_ARRAY);
strcpy(value,positionOfequal);
break;
}
}/* End of if(strstr(key,keyIntheFile)!=NULL)*/
memset(key,'\0',SIZE_OF_ARRAY);
}/* End of while (fscanf(FD_IniFileP,"%s",key)!= EOF)*/
}/* End of if( FD_IniFileP != NULL )*/
if (FD_IniFileP)
{
fclose(FD_IniFileP);
}
return value;
}
I think the statement "char *positionOfequal = strstr(key,"=");" can
show undefined behavior .
1) Is my understanding correct ?
I have another question
2) Can we pass directly sequence of characters to the function which
expects string ?
For example strcpy(dest,"some");
Strcat(dest,"abc"); ?
Regards,
Somenath
I was going through one piece of code which is written by an
experience programmer and it is working fine.
But I think the use of "strstr" is not proper because it may show
undefined behavior.
char *returnValueFromIniFile(char *iniFilePath,char *keyIntheFile)
{
FILE *FD_IniFileP =NULL;
char key[SIZE_OF_ARRAY]={'0'};
static char value[SIZE_OF_ARRAY]={'\0'};
FD_IniFileP = fopen(iniFilePath,"r");
if( FD_IniFileP != NULL )
{
/* File Open Success*/
while (fscanf(FD_IniFileP,"%s",key)!= EOF)
{
if(strstr(key,keyIntheFile)!=NULL)
{
/*Make sure key contains "="*/
if(strstr(key,"=")!=NULL)
{
/*Sepereate the key and the value */
char *positionOfequal = strstr(key,"="); /* as "="
is not terminated by '\0' it can show undefined behavior ? */
/*increment the positionOfequal to reach the
beganing of the value */
positionOfequal +=1;
assert(strlen(positionOfequal)<SIZE_OF_ARRAY);
strcpy(value,positionOfequal);
break;
}
}/* End of if(strstr(key,keyIntheFile)!=NULL)*/
memset(key,'\0',SIZE_OF_ARRAY);
}/* End of while (fscanf(FD_IniFileP,"%s",key)!= EOF)*/
}/* End of if( FD_IniFileP != NULL )*/
if (FD_IniFileP)
{
fclose(FD_IniFileP);
}
return value;
}
I think the statement "char *positionOfequal = strstr(key,"=");" can
show undefined behavior .
1) Is my understanding correct ?
I have another question
2) Can we pass directly sequence of characters to the function which
expects string ?
For example strcpy(dest,"some");
Strcat(dest,"abc"); ?
Regards,
Somenath