[英]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.