静态与Malloc [英] Static vs. Malloc

查看:105
本文介绍了静态与Malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与使用malloc相比,在块范围内使用static关键字有什么优势?

What is the advantage of the static keyword in block scope vs. using malloc?

例如:

功能A:

f() {
    static int x = 7;
}

功能B:

f() {
    int *x = malloc(sizeof(int));
    if (x != NULL)
        *x = 7;
}

如果我正确理解了这两个程序,则两个程序都会创建一个整数7,该整数存储在堆中.在A中,变量是在main方法执行之前从某个永久性存储的最开始创建的.在B中,一旦调用该函数,便立即在内存中分配内存,然后在该指针指向的位置存储7.在哪种情况下,您可能会使用一种方法而不是另一种方法?我知道您无法释放函数A中的x,所以这通常不会使B更可取吗?

If I am understanding this correctly, both programs create an integer 7 that is stored on the heap. In A, the variable is created at the very beginning in some permanent storage, before the main method executes. In B, you are allocating the memory on the spot once the function is called and then storing a 7 where that pointer points. In what type of situations might you use one method over the other? I know that you cannot free the x in function A, so wouldn't that make B generally more preferable?

推荐答案

这两个程序都创建一个integer 7,该integer 7存储在堆中

Both programs create an integer 7 that is stored on the heap

不,他们没有.
static创建一个具有静态存储持续时间的对象,该对象在程序的整个生命周期中都保持活动状态.动态分配的对象(由 创建的)保留在内存中,直到由free明确删除.两者均提供独特的功能. static在函数调用中维护对象的状态,而动态分配的对象则不维护.

No, they don't.
static creates a object with static storage duration which remains alive throughout the lifetime of the program. While a dynamically allocated object(created by malloc) remains in memory until explicitly deleted by free. Both provide distinct functionality. static maintains the state of the object within function calls while dynamically allocated object does not.

在哪种情况下,您可能会使用一种方法而不是另一种方法?

当您希望对象在程序的整个生命周期中都处于活动状态并在函数调用中保持其状态时,可以使用static.如果在多线程环境中工作,则同一static对象将为所有线程共享,因此需要同步.

You use static when you want the object to be alive throughout the lifetime of program and maintain its state within function calls. If you are working in a multithreaded environment the same static object will be shared for all the threads and hence would need synchronization.

当您明确想要控制对象的生存期时,请使用malloc.例如:确保对象生存足够长的时间,直到函数调用者在函数调用后对其进行访问为止.(一个自动/本地对象函数的作用域{ }结束后将被释放.)除非调用者显式调用free,否则分配的内存将泄漏,直到操作系统在程序退出时回收它为止.

You use malloc when you explicitly want to control the lifetime of the object.for e.g: Making sure the object lives long enough till caller of function accesses it after the function call.(An automatic/local object will be deallocated once the scope{ } of the function ends). Unless the caller explicitly calls free the allocated memory is leaked until the OS reclaims it at program exit.

这篇关于静态与Malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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