什么时候需要动态内存? [英] When do I need dynamic memory?

查看:285
本文介绍了什么时候需要动态内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Malloc还是常规数组定义?

Possible Duplicate:
Malloc or normal array definition?

我们了解到C和动态变量中都有动态内存:

We learn that there is dynamic memory in C and dynamic variables:

#include <stdio.h>
int a = 17;
int main(void)
{
  int b = 18; //automatic stack memory
  int * c;
  c = malloc( sizeof( int ) ); //dynamic heap memory
  *c = 19;
  printf("a = %d at address %x\n", a, &a);
  printf("b = %d at address %x\n", b, &b);
  printf("c = %d at address %x\n", *c, c);
  free(c);  
  system("PAUSE");  
  return 0;
}

我如何知道要使用哪种类型的内存?我什么时候应该一个或另一个?

How do I know which type of memory to use? When do I ned one or the other?

推荐答案

在以下情况下使用动态:

Use dynamic in the following situations:

  1. 当您需要大量内存时.典型的堆栈大小为1 MB,因此最好动态分配大于50-100KB的任何内容,否则您就有崩溃的风险.某些平台可以将此限制甚至更低.

  1. When you need a lot of memory. Typical stack size is 1 MB, so anything bigger than 50-100KB should better be dynamically allocated, or you're risking crash. Some platforms can have this limit even lower.

函数返回后必须保留内存的时间.函数结束时,堆栈内存将被销毁,您可以根据需要释放动态内存.

When the memory must live after the function returns. Stack memory gets destroyed when function ends, dynamic memory is freed when you want.

当您构建未知大小(即可能变大)的结构(例如数组或图形)时,会动态变化或难以进行预先计算.动态分配使您的代码可以随时随地自然地仅在需要时才请求内存.在for循环中不可能重复请求越来越多的堆栈空间.

When you're building a structure (like array, or graph) of size that is unknown (i.e. may get big), dynamically changes or is too hard to precalculate. Dynamic allocation allows your code to naturally request memory piece by piece at any moment and only when you need it. It is not possible to repeatedly request more and more stack space in a for loop.

否则,请优先选择堆栈分配.它更快并且不会泄漏.

Prefer stack allocation otherwise. It is faster and can not leak.

这篇关于什么时候需要动态内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆