考虑一下C中的这些代码:
int n;
scanf("\n%d ",&n);
int arr[n];还有这个。
int n;
scanf("\n%d ",&n);
int *p = (int *)malloc(n*sizeof(int)); 为什么我们首先需要动态内存分配?
当数组在运行时创建时,第一段代码不是动态内存分配吗?
何时使用malloc()?
发布于 2020-01-21 18:21:38
int arr[n]; 在堆栈上分配内存.是自动分配,然后在块末尾解除分配。。指向堆栈内存的指针不能安全地从函数返回。
考虑一下这个。
#include <stdio.h>
char *make_array() {
int n;
scanf("%d",&n);
// Memory for `arr` is allocated on the stack.
char arr[n];
// And then deallocated when the function exits.
// A good compiler and editor will warn you if you try
// to return it.
return arr;
}
int main() {
// This pointer is to memory which has already been freed. Other things
// will overwrite it.
char *arr = make_array();
arr[0] = 'c';
arr[1] = '\0';
// This could be the letter c, but it's probably gibberish.
puts(arr);
}如果需要内存超过当前函数的生命周期,则需要使用malloc在堆中分配内存并自己管理它。
发布于 2020-01-21 18:28:45
int n;
scanf("\n%d ",&n);
int arr[n];如果n是一个运行时动态值(在本例中是如此),则C的旧版本不支持它,这要求n是一个整数常量表达式。
现代版本的C已经取消了这个限制,允许动态大小的数组(可变长度数组,或VLA),但是与旧的固定大小数组不同,VLA有限制。
它们不允许被跳过(对于break/continue/goto),,它们可能不是异步信号安全的,如果它们太大,它们会使您的程序崩溃,并且它们通常会生成比普通的旧本地数组更大的代码。)
另外,因为它们是本地的,所以不能将指向调用方的指针返回给调用者。
尺寸限制是他们最大的限制之一。VLAs是从调用堆栈中分割出来的,调用堆栈通常只有几公斤/兆字节大,如果超过这个限制,就会出现典型的未诊断的崩溃。
mallocd内存没有这样的限制,malloc故障显然是通过返回的NULL报告的,而且由于mallocd内存对进程是全局的,所以可以将指向它的指针传递给调用方。
`
发布于 2020-01-21 18:17:37
int n;
scanf("\n%d ",&n);
int arr[n];如果它有效,那么这意味着您使用的编译器仍然将其解释为"DMA“,这里唯一的区别是它将在作用域结束时被解除分配,但我不认为这是C的一个好做法。
https://stackoverflow.com/questions/59846871
复制相似问题