Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
释放C中分配的内存时堆损坏_C_Memory_Memory Management_Memory Leaks - Fatal编程技术网

释放C中分配的内存时堆损坏

释放C中分配的内存时堆损坏,c,memory,memory-management,memory-leaks,C,Memory,Memory Management,Memory Leaks,为了在执行malloc命令后释放内存以防止内存泄漏,我在运行时遇到了堆损坏问题。我的调试告诉我,我的应用程序正在尝试在到达堆缓冲区末尾后写入内存。以下是我简化的内容,以隔离我的问题 #include <stdio.h> #include <stdlib.h> #include <math.h> main(){ int i,j,n; int temp[4]; int **a; printf("Amount of intervals to be entere

为了在执行malloc命令后释放内存以防止内存泄漏,我在运行时遇到了堆损坏问题。我的调试告诉我,我的应用程序正在尝试在到达堆缓冲区末尾后写入内存。以下是我简化的内容,以隔离我的问题

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

main(){

int i,j,n;
int temp[4];
int **a;

printf("Amount of intervals to be entered: ");
scanf("%d", &n);

//allocate memory for a 2d array of size (n x 4)
a = (int**) malloc(n*sizeof(int*));
for (i=0;i<4;i++){
    a[i] = (int*) malloc(4*sizeof(int));
}

if (!a){
    printf("malloc failed %d\n",__LINE__);
    exit(0);
}

printf("Please enter the intervals a line at a time followed by a return: \n");
for(i=0;i<n;i++){
    scanf("%d %d %d %d",&a[i][0], &a[i][1], &a[i][2], &a[i][3]);
}

for(i=0;i<n;i++){

    printf("%d, %d, %d, %d\n", a[i][0], a[i][1], a[i][2], a[i][3]);

}


// free up the allocated memory 


for (i=0;i<n;i++){
    free(a[i]);
}

free(a);




}
#包括
#包括
#包括
main(){
inti,j,n;
内部温度[4];
国际**a;
printf(“要输入的间隔量:”);
scanf(“%d”和“&n”);
//为大小为(nx4)的2d数组分配内存
a=(int**)malloc(n*sizeof(int*);

对于(i=0;i可能还有其他问题。但这至少是错误的:

a = (int**) malloc(n*sizeof(int*));
for (i=0;i<4;i++){                   <---- 4 should be n
    a[i] = (int*) malloc(4*sizeof(int));
}
a=(int**)malloc(n*sizeof(int*);

对于(i=0;i可能还有其他问题。但这至少是错误的:

a = (int**) malloc(n*sizeof(int*));
for (i=0;i<4;i++){                   <---- 4 should be n
    a[i] = (int*) malloc(4*sizeof(int));
}
a=(int**)malloc(n*sizeof(int*);
for(i=0;i
//为大小为(nx4)的2d数组分配内存
a=(int**)malloc(n*sizeof(int*);
如果(!a){
printf(“malloc失败%d\n”,第行);
出口(0);
}
for(i=0;i
//为大小为(nx4)的2d数组分配内存
a=(int**)malloc(n*sizeof(int*);
如果(!a){
printf(“malloc失败%d\n”,第行);
出口(0);
}

因为(我=0;我比它快55秒:-)非常感谢,我讨厌它如此简单,因为我觉得自己很愚蠢,但同时也很高兴:-)谢谢!比我快55秒:-)非常感谢,我讨厌它如此简单,因为我觉得自己很愚蠢,但同时也很高兴:)谢谢!释放内存通常是一个好主意,但值得注意的是,当程序退出时,所有内存都会隐式释放。(因此,从技术上讲,在这种情况下,您不需要释放任何内容。)释放内存通常是一个好主意,但也值得注意的是,当程序退出时,所有内存都会隐式释放。(因此,从技术上讲,在这种情况下,您不需要释放任何内容。)