gpt4 book ai didi

c - Malloc-释放后使用内存未触发错误

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

下面是我正在试用的 C 程序。它根据用户输入为所需数量的元素分配内存,为用户获取元素,打印元素和总和。

我在使用 ptr 之前使用 free 函数释放分配的内存。但是,它没有抛出任何错误,我能够成功地编译/运行、打印数组以及总和。我对 malloc 和 free 的理解是,如果我们释放分配的内存并尝试访问它,它应该在编译时抛出错误吗?请澄清这个疑问。谢谢。

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

int main(void){
int num=0;
int *ptr=NULL;
int sum=0;

printf("Enter number of elements in an array: \n");
scanf("%d",&num);

ptr = (int *)malloc(num*sizeof(int));

if (ptr==NULL){
printf("Error: unable to allocate memory\n");
exit(EXIT_FAILURE);
}

free(ptr); //ERROR NOT TRIGGERED

printf("Enter the elements of the array: \n");

for(int i=0;i<num;i++){
scanf("%d",(ptr+i));
sum += *(ptr+i);
}

printf("\nArray Elements are: \n");

for(int i=0;i<num;i++){
printf("%d ",*(ptr+i));
}

printf("\nSum of array elements are: %d\n", sum);
return 0;
}

最佳答案

既然您已经成功分配了内存,那么 free 绝对没有理由触发错误。然而,在那之后使用指针是未定义的行为,这意味着任何事情都可能发生,包括正常工作、崩溃、格式化硬盘或将令人反感的图像发送到老板的电子邮件中。当然,最后两件事永远不会发生,但 C 规范中没有任何内容说它不能。未定义的行为是未定义的。

在指针上调用free 基本上意味着您保证不再使用该内存。如果你违背了那个 promise ,那么,后果自负。

编译通过并不奇怪。如果出错,它将在运行时出错。

关于c - Malloc-释放后使用内存未触发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48089152/

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