[英]Not allocating memory for pointers, is this causing my segmentation fault (core dumped) in C?
我可以在Eclipse的Windows計算機上運行它,但是當我嘗試在Unix計算機上運行它時,出現“分段錯誤(核心已轉儲)”。 如何找到導致錯誤的行? 我閱讀了此頁面http://www.cs.mun.ca/~michael/c/problems.html ,其中說這可能是由於未為指針分配內存,但是在嘗試使用char *users[1000];
時出現錯誤char *users[1000];
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_CHANGE (10.0/86400.0) /* 10kg/day */
/* seconds in a day is 24 hours * 60 minutes * 60 seconds */
main() {
char line[1024];
char lineC[1024];
int countToken = 0;
int lasttime = 0;
char *tokens;
char *users;
int timestamp;
int duration;
char userID[1000];
char lastuser[1000];
float weight;
float lastweight;
float change;
float changePerTime;
while (fgets(line,1024,stdin) != NULL) {
strcpy(lineC, line);
tokens = strtok(line, " ");
sscanf(tokens, "%d", ×tamp); //first token is timestamp
while(tokens != NULL){
countToken++;
tokens = strtok(NULL, " ");
}
int countTemp = countToken;
users = strtok(lineC, " ");
while(countTemp > 1){
if(countTemp == countToken){
countTemp--;
}
else{
users = strtok(NULL, " .0123456789");
strcat(userID, users);
countTemp--;
}
}
users = strtok(NULL, " ");
sscanf(users, "%f", &weight);
if (countToken < 1 || timestamp == 0) {
printf("Invalid time\n");
continue;
}
else if (countToken < 2 || ! (isalpha(userID[0]) || userID[0] == '_') )
printf("Illegal userID\n");
else if (countToken < 3 || weight < 30.0 || weight > 300.0)
printf("Illegal weight\n");
else if (lasttime >= timestamp)
printf("Nonmonotonic timestamp\n");
else {
duration = timestamp - lasttime;
change = weight - lastweight;
changePerTime = change / duration;
int g = strcmp(lastuser, userID);
if (lasttime > 0 && (changePerTime < -MAX_CHANGE || changePerTime > MAX_CHANGE) && (g==0))
printf("Suspiciously large weight change\n");
else
printf("OK\n");
lastweight = weight;
lasttime = timestamp;
}
strcpy(lastuser, userID);
lasttime = timestamp;
countToken = 0;
strcpy(userID, "");
}
}
有時可能很難開始為新平台進行開發,但是一旦您了解了基本概念,它就和其他平台一樣容易。 :)
我建議您執行以下操作:
您正在濫用NULL指針,並且在修復代碼之前,請先閱讀有關指針(特別是NULL指針)的更多信息,然后選中此按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.