为什么函数可以通过malloc返回一个数组设置,而不能通过"int cat [3] = {0,0,0};"返回一个设置. [英] Why can a function return an array setup by malloc but not one setup by "int cat[3] = {0,0,0};"

查看:72
本文介绍了为什么函数可以通过malloc返回一个数组设置,而不能通过"int cat [3] = {0,0,0};"返回一个设置.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我可以从函数中返回malloc设置的数组:

Why can I return from a function an array setup by malloc:

int *dog = (int*)malloc(n * sizeof(int));

但不是由...设置的数组

but not an array setup by

 int cat[3] = {0,0,0};

"cat []"数组返回警告.

The "cat[ ]" array is returned with a Warning.

感谢您的帮助

推荐答案

正在运行的程序中有两个关键的内存部分: stack heap . stack 也称为 call stack .

There are two key parts of memory in a running program: the stack, and the heap. The stack is also referred to as the call stack.

进行函数调用时,会将有关参数,返回位置以及在函数范围内定义的所有变量的信息推入到堆栈中. (过去通常只能在函数的开头定义C变量.主要是因为它使编译器编写者的工作更加轻松.)

When you make a function call, information about the parameters, where to return, and all the variables defined in the scope of the function are pushed onto the stack. (It used to be the case that C variables could only be defined at the beginning of the function. Mostly because it made life easier for the compiler writers.)

从函数返回时,堆栈上的所有内容都会被弹出并消失(很快,当您进行更多函数调用时,您将覆盖该内存,因此您不想指着它!)

When you return from a function, everything on the stack is popped off and is gone (and soon when you make some more function calls you'll overwrite that memory, so you don't want to be pointing at it!)

每次分配内存时,都是从 heap 中分配内存.那是内存的其他部分,由分配管理器维护.一旦保留"它的一部分,就应对它负责,如果您想停止指向它,则应该让经理知道.如果您放下指针而又不要求释放指针,那就是泄漏.

Anytime you allocate memory you are allocating if from the heap. That's some other part of memory, maintained by the allocation manager. Once you "reserve" part of it, you are responsible for it, and if you want to stop pointing at it, you're supposed to let the manager know. If you drop the pointer and can't ask to have it released any more, that's a leak.

您还应该只查看您想要的内存部分.覆盖不仅是您想要的部分,而且覆盖内存的那部分(或之前)是一种典型的利用方法:将信息写入存储着计算机指令而不是数据的内存部分.了解编译器和运行时如何管理事物的知识有助于专家弄清楚如何做到这一点.设计良好的操作系统会阻止他们这样做.

You're also supposed to only look at the part of memory you said you wanted. Overwriting not just the part you said you wanted, but past (or before) that part of memory is a classic technique for exploits: writing information into part of memory that is holding computer instructions instead of data. Knowledge of how the compiler and the runtime manage things helps experts figure out how to do this. Well designed operating systems prevent them from doing that.

堆:

int *dog = (int*)malloc(n*sizeof(int*));

堆栈:

int cat[3] = {0,0,0};

这篇关于为什么函数可以通过malloc返回一个数组设置,而不能通过"int cat [3] = {0,0,0};"返回一个设置.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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