提问人:notCyberV 提问时间:10/20/2023 最后编辑:notCyberV 更新时间:10/20/2023 访问量:62
C 错误 free():在数组操作的 tcache 2 中检测到双重释放
C error free(): double free detected in tcache 2 in an array manipulation
问:
需要做什么
我的函数被赋予一个 n 个数字的数组,应该创建并返回一个新数组,其内容取决于参数 k:
如果 k>0,则新数组必须连续包含重复 k 次的每个数字;例如,如果 a=[1, 0, 8, 2] 且 k=3,则新数组必须为 [1 1, 1, 0, 0 0, 0 8, 8, 8, 2, 2]
如果 k=0,则新数组的长度必须与 a 相同,但只包含零;例如,如果 a=[1, 0, 8, 2] 且 k=0,则新数组必须为 [0, 0, 0, 0]
如果 k<0,则新数组必须包含重复 k 次的每个元素,但顺序相反;例如,如果 a=[1, 0, 8, 2] 且 k=-2,则新数组必须为 [2, 2, 8, 8, 0, 0, 1, 1]
该函数必须返回指向结果数组的第一个元素的指针,并将其长度存储在 *newn 中。
main 函数必须从命令行读取输入文件的名称和一系列整数 integer1、integer2、...integerK,然后将存储在输入文件中的整数读入数组(如果没有整数,则终止)
对于命令行上的每个整数,它调用函数,向它传递数组和整数,并将 elaborate 返回的数组元素写入 stdout。程序不应将任何其他内容打印到 stdout,在 stderr 中调试消息
例如,如果程序是通过写入elabora
main test1 2 0 -1
并且 infile 包含整数
2
0
5
1
程序必须打印 3 行
2 2 0 0 5 5 1 1
0 0 0 0
1 5 0 2
程序必须关闭所有文件并解除分配所有已使用的内存。
这是我的代码
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
void termina(const char *messaggio);
int *elabora(int a[], int n, int k, int *nuovon) {
int c = 0;
nuovon = malloc(n*sizeof(int));
if(nuovon==NULL) termina("Memoria insufficiente");
for(int i=0; i<n; i++) {
if(k>0) {
for(int j=0; j<k; j++) {
nuovon[c]=a[j];
c++;
}
} else if(k==0) {
nuovon[c] = 0;
c++;
} else {
for(int j=k-1; j>=0; j--) {
nuovon[c]=a[j];
c++;
}
}
}
*nuovon = n*k;
return nuovon;
}
int main(int argc, char *argv[])
{
if(argc<2) {
fprintf(stderr, "Uso: %s i1 [i2 i3 ...]\n", argv[0]);
exit(1);
}
int n = 10;
int *nuovon = NULL;
int k = atoi(argv[2]);
int i;
int *a = malloc(n*sizeof(int));
if(a==NULL) termina("Memoria insufficiente");
// lettura file
FILE *f = fopen(argv[1], "r");
if(f==NULL) termina("Impossibile aprire il file di inpt");
// lettura interi
int e = fscanf(f, "%d", &n);
if(e!=1) {
termina("Non ci sono interi nel file");
fprintf(stderr, "Errore di lettura nella riga %d\n", i);
}
//chiusura file
fclose(f);
for(int i=2; i<argc; i++) {
nuovon = elabora(a, n, k, nuovon);
for(int j=0; j<n*k; j++) {
fprintf(stdout, "%d", nuovon[j]);
}
}
free(nuovon);
free(a);
return 0;
}
void termina(const char *messaggio){
if(errno!=0) perror(messaggio);
else fprintf(stderr,"%s\n", messaggio);
exit(1);
}
错误
当我运行它时,它没有给我任何警告,因为我修复了它们,但现在它只显示一些随机的 0 作为输出。main test1 2 0 5 1
答: 暂无答案
评论
free(nuovon); return nuovon; *nuovon = n*k;
free(nuovon)
free(nuovon); return nuovon; *nuovon = n*k;
fclose()
fclose(f); if(fclose(f)!=0)
free(nuovon)
return