I am able to run it on my windows computer in eclipse, but when I try running it on a Unix computer I get "Segmentation fault (core dumped)". How can I find which line is causing the error? I read this page http://www.cs.mun.ca/~michael/c/problems.html which says it could be due to not allocating memory for pointers, but I am getting errors when I try for example 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, "");
}
}
Sometimes it can be hard to start developing for a new platform, but once you understand the basic concepts it is just as easy as any other platform. :)
I would recommend you to do the following:
您正在滥用NULL指针,并且在修复代码之前,请先阅读有关指针(特别是NULL指针)的更多信息,然后选中此按钮。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.