【发布时间】:2014-10-06 15:16:02
【问题描述】:
所以我很好奇为什么以下代码段不断出现段错误。在我看来是正确的。
int * addCoins(char *val){
const char *deli = ",";
char *ptr =NULL;
char *denomination = strtok_r(val, deli, &ptr);
char *count = strtok_r(NULL, deli, &ptr);
int deno = atoi(denomination);
int cnt = atoi(count);
int *k;
k = malloc(sizeof(*k)*2);
k[0] = deno;
k[1] =cnt;
return k;
}
在 main 中调用 addCoins 函数。我认为问题不在于这里,但老实说,我对这个问题有点不知所措。
char* fileNameCoin = argv[2];
FILE *fileCoin;
fileCoin = fopen(fileNameCoin, "r+");
char bufCoin[256];
int i = 0;
//vmNode->next = NULL;
int *j;
while (fgets(bufCoin, sizeof bufCoin, fileCoin) != NULL) {
j = addCoins(bufCoin);
int deno = j[0];
switch(deno){
case 5:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 10:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 20:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 50:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 100:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 200:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 500:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 1000:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
default:
break;
}
i++;
}
以下是文件的定义方式
1000,3
500,4
200,20
100,30
50,5
20,3
10,40
5,20
其中第一个数字是以美分为单位的面额,第二列是所述面额的数字。
这些是 typedef:
/* The different denominations of coins available */
enum denomination
{
FIVE_CENTS, TEN_CENTS, TWENTY_CENTS, FIFTY_CENTS, ONE_DOLLAR,
TWO_DOLLARS, FIVE_DOLLARS, TEN_DOLLARS
};
/* Each coin in the coins array will have a denomination (20 cents,
* 50 cents, etc) and a count - how many of that coin do we have on hand
*/
struct coin
{
enum denomination denom;
unsigned count;
};
【问题讨论】:
-
段错误到底发生在哪里?
-
发生在 addCoins 函数中,在 strtok_r 行。
-
你像筛子一样泄漏内存;您应该在循环末尾包含
free(j);。你可以折叠你的switch,这样case 5: case 10: case 20: case 50: case 100: case 200: case 500: case 100: Coins[i].denom = j[0]; Coins[i].count = j[1]; break;。我不确定简单地忽略错误数据是个好主意。也报错。并检查来自strtok_r()的返回值——但使用它而不是strtok()做得很好。文件打开成功的检查在哪里? -
您可能希望使用符号编译并使用调试器。
-
"发生在 addCoins 函数中,在 strtok_r 行。" 有两行! 叹息
标签: c segmentation-fault strtok