问题:当我试图编译我的文件并运行时,它有分段问题。当我把文件传给 friend (他用的是同一版本的ubuntu),服务器就可以运行了。我想知道为什么?
下面是我的整个页面的代码。 个人感觉没什么问题,不过我贴出来供大家引用。
void readNStoreData ()
{
char words[MAX];
char *wholeLine;
char* delimiter = ",";
int cflag = 0;
int x, count = 0;
char input;
FILE *countryFile;
countryFile = fopen("Countries.txt","r");
if (!countryFile) {
exit(EXIT_FAILURE);
}
while (fgets (words, MAX - 1, countryFile) != NULL)
{
//atof to convert string to double
//split a single line into individual tokens indicating , as the delimeter
//afterwards store them into array
wholeLine = strtok (words, delimiter);
strcpy (records [count].TDL, wholeLine);
wholeLine = strtok (NULL, ",");
strcpy (records [count].cName, wholeLine);
wholeLine = strtok (NULL, delimiter);
strcpy (records [count].FIPS104, wholeLine);
wholeLine = strtok (NULL, delimiter);
strcpy (records [count].ISO2, wholeLine);
wholeLine = strtok (NULL, delimiter);
strcpy (records [count].ISO3, wholeLine);
wholeLine = strtok (NULL, delimiter);
records [count].ISO = atof(wholeLine);
wholeLine = strtok (NULL, delimiter);
strcpy (records [count].cCapital, wholeLine);
wholeLine = strtok (NULL, delimiter);
strcpy (records [count].cRegion, wholeLine);
wholeLine = strtok (NULL, delimiter);
strcpy (records [count].cCurrencyName, wholeLine);
wholeLine = strtok (NULL, delimiter);
strcpy (records [count].cCurrencyCode, wholeLine);
wholeLine = strtok (NULL, delimiter);
records [count].cPopulation = atof(wholeLine);
count++;
}
fclose(countryFile); //close file
}
我希望有人能够在某处发现错误。 感谢提前帮助过的人!
运行gdb,错误其实是这一行。 它位于此函数中。
l(gdb) frame 1
l#1 0x08048936 in readNStoreData () at testserver.c:61
61 strcpy (records [count].cName, wholeLine);
最佳答案
我强烈建议你学习使用debugger ,例如 GDB .您可以通过 sudo apt-get install gdb
这是一个简短的tutorial .
编辑:
既然你现在已经运行了 GDB,试着设置一个 breakpoint在运行
之前:
(gdb) br testserver.c:61
在您运行
之后,您应该能够打印
各种变量并查看哪个变量是非法的。
关于linux - 段错误很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9211513/