gpt4 book ai didi

c - 内存泄漏,段错误,C

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:07 25 4
gpt4 key购买 nike

gcc 显示 0 个错误,但 valgrind 显示内存泄漏,我无法执行我的程序,因为段错误(核心转储)有什么建议吗?我单独检查了分配,它很好的 valgrind 显示 0 内存泄漏。文件操作中某处有问题,但我找不到它。

#include <stdio.h>
#include <stdlib.h>

int* arrsize(FILE *plik)
{
if (plik == NULL) {
printf("Error: file pointer is null.");
return 0;
}
int* size;
fscanf(plik, "%d", &size);
return size;
}


int main()
{
int i = 0, j = 0, k = 0, a = 0;

FILE *fp;
if ((fp = fopen("matrix.txt", "r")) == NULL)
{
printf("Error: file pointer is null.\n");
return 1;
}
int size = arrsize(fp);

printf("Array size is %d x %d ", size, size);



double **arr = (double **)malloc(size * sizeof(double *));
for (i; i < size; i++)
arr[i] = (double *)malloc(size * sizeof(double));


for (j; j < size; j++) {
fscanf(fp, "%d", &arr[i][j]);
}



for (i; i < size; i++)
{
for (j = 0; j < size; j++)
{

printf("%lf\n", &arr[i][j]);
}
}

for (k; k < size; k++) {
free(arr[k]);
}
free(arr);

fclose(fp);

return 0;
}

最佳答案

更改 arrsize 以实际返回 int,而不是 int*:

int arrsize(FILE *plik)
{
if (plik == NULL) {
printf("Error: file pointer is null.");
return 0;
}
int size;
fscanf(plik, "%d", &size);
return size;
}

关于c - 内存泄漏,段错误,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46759866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com