我有3个问题:
userHostPairs[count]=line
会给出不希望的结果,如代码注释中所述? #define MAX_HOSTS 100
#define MAX_LINE_SIZE 100
void readEnvList()
{
FILE *fp;
char line[MAX_LINE_SIZE];
char* userHostPairs[MAX_HOSTS];
if((fp = fopen("somefile", "r")) == NULL)
{
//ERR_StdReportAndReturn_2(OPIGN_FILE_FAILURE ,"write", schScriptFileName);
printf("Failed to open the file\n");
}
int count =0;
while (fgets(line, sizeof(line), fp) != NULL ) {
//userHostPairs[count]=line; --Assignment like this gives undefined results. e.g. at the end of the loop userHostPairs[0] & userHostPairs[1] both contain the last fetched line from file.
strcpy(userHostPairs[count],line);
count++;
}
printf("%s",userHostPairs[0]); //CORE DUMP here
}
int main()
{
readEnvList();
}
答案 0 :(得分:2)
在您的代码中
strcpy(userHostPairs[count],line);
您正试图写入指向不确定地址的统一指针(userHostPairs[count]
)。因此,在您的程序上下文中,内存位置为无效,并尝试写入无效的内存位置会调用undefined behavior。
您需要