自由整数列表

Free list of integers

我试图释放一个从头部开始的整数列表,并且知道列表中有多少元素,但我收到无效指针错误。 代码如下:

int* factors = job_factorization(number, size);
printf("Thread %d: job terminated. Result: ", params->thread_id);
int* tmp;
for (int i = 0; i < *size; i++){
    printf("%d ", *factors);
    tmp = factors;
    factors++;
    free(tmp);
}

int *job_factorization(int number, int *size) {
    int *factors;
    int array_size = SIZE_INCREASE;
    int factor = 2;

    if (number < 2)
        return NULL;

    factors = (int *) malloc(sizeof(int) * SIZE_INCREASE);
    *size = 0;

    while (number != 1) {
        // check whether the number is divisible by the factor
        if (number % factor == 0) {
            // if there is no more space available, resize the array
            if (*size == array_size) {
                array_size += SIZE_INCREASE;
                factors = (int *) realloc(factors, sizeof(int) * array_size);
            }
            // add the factor to the list of prime factors
            factors[*size] = factor;
            (*size)++;
            number = number / factor;
        }
        else {
            // if not a factor, move to the next prime number
            factor = next_prime(factor);
        }
    }
    return factors;
}

有人知道发生这种情况的原因吗?我对此一无所知(函数 job_factorization 工作正常)

job_factorization 构成一个 malloc(以及多个 realloc)。对于 job_factorization 的用户来说,这看起来只是一次分配,而且只需要一次 free。像这样:

int* factors = job_factorization(number, size);

for (int i = 0; i < *size; i++) {
    printf("%d ", factors[i]);     // don't increase factors in the loop
}

free(factors);                     // one free

当你使用 realloc 时,它会替换旧的分配,所以如果你先 malloc 用于 1 元素,然后 realloc 用于 2 元素,结果是一次分配 2 个元素——只需要一个 free 个。