Failsafe Allocation

醉酒当歌 提交于 2020-01-05 12:16:18

问题


I am working on windows XP. So I understand that auto variables are stored on the stack and the dynamically generated data of the pointer variables are stored on the heap.

Is the amount of stack memory and heap memory available to each program fixed. Can it be set different for a particular program? If yes then -> Is the setting done automatically by the system or does it have to be done manually in some way?

I am planning to create a huge array(say 50000 records) of a structure in C. I can only think of declaring it as one of the following:

  1. global and statically created eg. struct Product products[50000];
  2. local and dynamically created eg. struct Product *products; products = malloc(sizeof(struct Product)*50000);

I just know that:

  • Calling too many functions(recursive or plain one in another) can use up the stack memory available.
  • Malloc can fail meaning enough heap memory was not available.

Am I right?

The scenario is that the application would be open along with many others on the system. I do not want this application to crash because of lack of memory. So what would be the failsafe way to have a huge array and eat it too?


回答1:


Dynamic allocation takes (virtual) RAM from the operating system as needed.

You can control the maximum stack size by the /F compiler switch.




回答2:


50000 structures is not that big. You will not have any problems allocating them. For this task use the dynamic allocation:

struct Product *products = malloc(sizeof(struct Product)*50000);

This way it will be easier for you to access your data as you have a pointer to it so you can pass it whenever you want. Moreover mallocreturns NULL when an allocation fails so you handle allocation errors.

Although your RAM is limited, you do not use any memory to make a dynamic allocation. For the static declaration, it is supposed not to fail usually but yet again your computer has some physical limits. But you are not going to reach them.



来源:https://stackoverflow.com/questions/24931859/failsafe-allocation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!