简体   繁体   English

在最后一行代码上出现段错误

[英]Seg fault on last line of code

I'm hoping to implement a simple molecular dynamics program. 我希望实施一个简单的分子动力学计划。 My first step is to define the system as a series of atoms, each with a type, an id number, a 3 dimensional position vector, and a 3D velocity vector. 我的第一步是将系统定义为一系列原子,每个原子都有一个类型,一个id号,一个​​3维位置矢量和一个3D速度矢量。 Below is the program I've written to do so: 以下是我写的程序:

FILE *init;

static int randomVelocity(void)  
{  
     return rand()/RAND_MAX - 0.5;  
}  


int main(int argc, char *argv[])  
{  

    int iType;  
    int iID;  
    int i;  
    double* pdPosition;  
    double* pdVelocity;  
    char* line;  
    Atom* poAtoms;  
    int count = 0;  

    init = fopen("newdat.txt", "r+");  
    srand((unsigned)time(NULL));  
    line = malloc(81*sizeof(char));  
    while (fgets(line, 80, init) != NULL)    
    {  
         char* tok1;  
         char* tok2;  
         char* tok3;  
         char* tok4;  
         tok1 = strtok(line, " \t");  
         if ((tok1 == NULL) || (tok1[0] == '*'))   
         {  
              break;  
         }  
         tok2 = strtok(NULL, " \t");  
         tok3 = strtok(NULL, " \t");  
         tok4 = strtok(NULL, " \t");  
         iType = atoi(tok1);  
         iID = count;  
         pdPosition = (double*)malloc(3*sizeof(double));  
         pdVelocity = (double*)malloc(3*sizeof(double));     
         pdPosition[0] = atof(tok2);  
         pdPosition[1] = atof(tok3);  
         pdPosition[2] = atof(tok4);  
         pdVelocity[0] = randomVelocity();  
         pdVelocity[1] = randomVelocity();    
         pdVelocity[2] = randomVelocity();  
         poAtoms[count] = Atom_new(iType, iID, pdPosition, pdVelocity);  
         count++;  
    }  

    for (i = 0; i < count; i++)  
    {  
         Atom_print(poAtoms[i]);  
         Atom_free(poAtoms[i]);  
    }   

    free(line);  
    return 0;  
}

Here is the header file atom.h: 这是头文件atom.h:

/**** atom.h ****/


typedef struct Atom_str *Atom;  

Atom Atom_new(int iType, int iID, double* adPosition, double* adVelocity);  

void Atom_free(Atom oAtom);  

void Atom_print(Atom oAtom);  

and the test input file: 和测试输入文件:

1 5 7 9  
2 12 13 14  

The program compiles, but when I run it, I get the expected output followed by a seg fault. 程序编译,但是当我运行它时,我得到预期的输出后跟一个seg错误。 I'm using the GDB debugger, and the seg fault appears to happen on the very last line of code, after the return statement! 我正在使用GDB调试器,并且在返回语句之后,seg错误似乎发生在最后一行代码上! Is it a memory management issue? 这是内存管理问题吗?

You've never malloc ed memory for poAtoms . 你从来没有malloc ED的内存poAtoms Writing to wherever that uninitialized pointer points can easily cause a segfault. 写入未初始化指针指向的位置很容易导致段错误。

Before you start reading the file, you should allocate some space, 在开始阅读文件之前,您应该分配一些空间,

unsigned expected_count = 2; // for the test input file, would be much larger in real runs
poAtoms = malloc(expected_count*sizeof(*poAtoms));

And then you have to check inside the read-loop that you're not writing past the allocated memory. 然后你必须在读循环内检查你没有写过分配的内存。 Before 之前

    poAtoms[count] = Atom_new(iType, iID, pdPosition, pdVelocity);

insert a check, 插入支票,

    if (expected_count <= count)
    {
        expected_count *= 2;   // double the space, could also be a smaller growth factor
        Atom *temp = realloc(poAtoms, expected_count*sizeof(*poAtoms));
        if (temp == NULL)
        {
            perror("Reallocation failed, exiting\n");
            exit(EXIT_FAILURE);
        }
        poAtoms = temp;
    }

if the allocated space for poAtoms is already used, try to get more with realloc , if that fails, abort unless you know how to fix it. 如果已经使用了poAtoms的已分配空间,请尝试使用realloc获取更多内容,如果失败,则中止,除非您知道如何修复它。 If the reallocation succeeds, we can continue collecting new atoms. 如果重新分配成功,我们可以继续收集新原子。

What is tok1[0] doing in if condition ? 什么是tok1 [0]在if条件下做什么? Did you check a small code snippet for strtok that what is returned or checked when you try to print tok1[[0]? 您是否检查了strtok的小代码片段,当您尝试打印tok1 [[0]时,返回或检查了什么?

Can you explain what does 1 5 7 9 represent in input file ? 你能解释1 5 7 9在输入文件中的含义吗? are thei type id and velocity . 是我的类型id和速度。 If so you can manipulate and differentiate them by hyphen and extract each value by strtok as NULL. 如果是这样,您可以通过连字符操作和区分它们,并将每个值提取为strtok为NULL。 Also check if fgets is appending NULL or may be * as you have tried to check in if condition probably for End of line . 同时检查fgets是否附加NULL或者可能是*,因为您尝试检入条件是否可能为行尾。 I have a gut felling that it can be the place where you are going wrong , Or if you can pleas explain your input file it would be helpful 我有一个直觉,它可能是你出错的地方,或者你可以请求解释你的输入文件,这将是有帮助的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM