并非将记忆分配给指针,而是导致我的分割故障(核心倾倒)



我能够在Eclipse的Windows计算机上运行它,但是当我尝试在Unix计算机上运行它时,我会得到"分割故障(core dustped)"。我如何找到导致错误的行?我读了此页面http://www.cs.mun.ca/~michael/c/problems.html,这可能是由于不为指针分配记忆,但是当我尝试char *users[1000]; <br时,我会遇到错误>

#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", &timestamp);   //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 timen");
            continue;
            }
        else if (countToken < 2 || ! (isalpha(userID[0]) || userID[0] == '_') )
            printf("Illegal userIDn");
        else if (countToken < 3 || weight < 30.0 || weight > 300.0)
            printf("Illegal weightn");
        else if (lasttime >= timestamp)
                printf("Nonmonotonic timestampn");
        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 changen");
            else
                printf("OKn");
            lastweight = weight;
            lasttime = timestamp;
            }
        strcpy(lastuser, userID);
        lasttime = timestamp;
        countToken = 0;
        strcpy(userID,  "");
    }
}

有时很难开始为新平台开发,但是一旦您了解了基本概念,它就与任何其他平台一样容易。:)

我建议您进行以下操作:

  1. 用调试符号编译代码。这将使您能够调试与VS中的方式相似。使用GCC编译器(以及其他一些),您应该使用-g参数来执行此操作。
  2. 配置您的终端以生成核心。Coredump是崩溃时过程状态的确切副本。启用此功能取决于您使用的终端(bash,csh等),但是您可以尝试以下内容:" ulimit"," limits"," limit'
  3. '
  4. 运行GDB。如果您使用-g参数进行编译,并且有Coredump,则可以执行'gdb -c coredump_filename binaryfilename',它将带您完全进入导致崩溃的线路2.另外,您可以从GDB" GDB binaryfilename"运行程序,并步骤每行直到程序崩溃。

您正在滥用空指针,然后在修复代码之前,请阅读有关指针特定零指针的更多信息,请检查此信息了解无效指针

相关内容

  • 没有找到相关文章

最新更新