Allocating Memory on the heap and stack

            Allocating memory on the heap

#include <stdlib.h>
  void *calloc(size_t numitems , size_t size );
      Returns pointer to allocated memory on success, or NULL on error

 

Example:

struct { /* Some field definitions */ } myStruct;
struct myStruct *p;
p = calloc(1000, sizeof(struct myStruct));
if (p == NULL)
  // error;

 

#include <stdlib.h>
  void *realloc(void * ptr , size_t size );
      Returns pointer to allocated memory on success, or NULL on error

  The call realloc(ptr, 0) is equivalent to calling free(ptr) followed by malloc(0). If
ptr is specified as NULL , then realloc() is equivalent to calling malloc(size).

Since realloc() may relocate the block of memory, we must use the returned
pointer from realloc() for future references to the memory block. We can employ
realloc() to reallocate a block pointed to by the variable ptr as follows:
  nptr = realloc(ptr, newsize);
  if (nptr == NULL) {
  /* Handle error */
  } else {
  /* realloc() succeeded */
  ptr = nptr;
  }

--------------------------------------------------------------------------------------------------------------------------------

          Allocating memory on the stack

#include <alloca.h>
  void *alloca(size_t size );
      Returns pointer to allocated block of memory ----- allocates memory dynamically

If the stack overflows as a consequence of calling alloca(), then program behavior is
unpredictable. In particular, we don’t get a NULL return to inform us of the error.
(In fact, in this circumstance, we may receive a SIGSEGV signal.)

Advantage of alloca() is that the memory that it allocates is automati-
cally freed when the stack frame is removed; that is, when the function that called
alloca() returns.

 

转载于:https://www.cnblogs.com/BurgundyRed/p/9588708.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值