BeagleBone 上的分段错误 SIGSEGV 错误

Segmentation fault SIGSEGV error on BeagleBone

我仍然遇到 C 代码中的分段错误问题。当我第 8 次调用函数 current_live_read(ainpath); 时出现错误:No source available for "_int_malloc() at 0x25be2" 主要功能如下所示:

void current_read(void)
{

    system(AINinit);

    char *ainpath;
    ainpath=init_current();

    int *current;
    float avgcurr=0;
    float allcurr=0;
    int i=0;

    while(1)
    {
    //sleep(1);
    i++;
    current=current_live_read(ainpath);
    allcurr=allcurr+*current;
    avgcurr=allcurr/i;
    printf("\n Current: %d AVG: %f", *current, avgcurr);
    //free(current);
    }

}

current_live_read(ainpath);是这样的:

int *current_live_read(char *ainpath)
{

    //ainpath=init_current();
    int curr;

    FILE *file = fopen(ainpath, "r");
    //free(ainpath);

    if(!file)
    {
        printf("Error opening file: %s\n", strerror(errno));
    }
    else
    {
        fscanf(file, "%4d", curr);
        fclose(file);
        //*current=curr;
    }

    free(file);


    return curr;
}

我知道指针可能有问题,但我不知道是哪一个以及我能做些什么。

您不能在关闭后释放 FILE * 指针。来自联机帮助页:

Flushes a stream, and then closes the file associated with that stream. Afterwards, the function releases any buffers associated with the stream. To flush means that unwritten buffered data is written to the file, and unread buffered data is discarded.

所以 fclose() 已经根据需要进行清理以防止内存泄漏。如果你在那个指针上调用 free(),你很可能会破坏你的堆。所以只需删除 free(file);

此外,您必须像这样将 指针 传递给 fscanf()

fscanf(file, "%4d", &curr);

否则你写入一个(伪)随机内存地址。检查 fscanf() 的 return 值以查看转换是否成功并适当地处理错误情况通常是个好主意。

这应该可以解决问题。

所以我把int *current_live_read(char *ainpath);改成没有指针类型的int current_live_read(char *ainpath)。 制作内部功能: int curr; fscanf(file, "%x", &curr) 在 main 函数中,电流只是整数: int current;