程序以信号 SIGABRT 终止,中止

Program terminated with signal SIGABRT, Aborted

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    int **seqList, n, q;
    scanf("%d %d", &n, &q);
    seqList = (int**)malloc(n * sizeof(int*));
    int *l_sub_seq = (int*)calloc(n, sizeof(int));//length of subsequences of all sequences                                              
    int lastAnswer = 0;

    while(q--)
    {
        int type, x, y, i;
        scanf("%d %d %d", &type, &x, &y);
        i = (x^lastAnswer) % n;
        switch(type)
        {
            case 1:
            l_sub_seq[i]++;
            seqList[i] = (int*)realloc(seqList[i], sizeof(int)*l_sub_seq[i]);
            seqList[i][l_sub_seq[i] - 1] = y;
            break;

            case 2:
            lastAnswer = seqList[i][y%l_sub_seq[i]];
            printf("\n");
            break;
        }
    }
    for(int i = 0; i < n; i++)
        free(seqList[i]);
    free(seqList);

    for(int i = 0; i < n; i++)
        free(l_sub_seq);

    return 0;
}

编译器信息:

free(): double free detected in tcache 2
Reading symbols from Solution...done.
[New LWP 335079]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGABRT, Aborted.
#0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50

您的代码可能至少在一个位置调用未定义的行为,并且肯定在另一个位置调用它。

realloc 允许输入指针值是:

  1. NULL
  2. malloccallocrealloc
  3. 返回的值

您的初始分配seqList

seqList = (int**)malloc(n * sizeof(int*));

创建一个指向 int 的指针序列。这些指针是 indeterminate(它们没有确定的值,无论是 NULL 还是任何其他有效值)可以传递给 realloc。因此,稍后在代码中执行此操作时:

seqList[i] = (int*)realloc(seqList[i], sizeof(int)*l_sub_seq[i]);
here ======================^^^^^^^^^^

您正在调用未定义的行为。您可以通过使用零填充 calloc(最简单)或循环、memset 等方式确保您的初始数组内容为空填充来解决此问题。

稍后,在你的程序结束时,你这样做:

for (int i = 0; i < n; i++)
    free(l_sub_seq);

那是胡说八道。 l_sub_seq 分配给:

int *l_sub_seq = (int*)calloc(n, sizeof(int));

它应该被释放一次,而不是在某个循环中,反复将相同的指针值一遍又一遍地传递给free

free(l_sub_seq); // no loop.

您的程序是否 "works" 由您决定,但您的终止问题的原因可能来自上述问题。