使用malloc()和free()函数分配和释放内存

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLOCKSIZE 300000000

int main(void){
  void *ptr1, *ptr2;
  
  // 分配一个内存块
  ptr1 = malloc(BLOCKSIZE);
  if(ptr1 != NULL){
    printf("\nFirst allocation of %d bytes successful.", BLOCKSIZE);
  } else {
    printf("\nAttemp to allocate %d bytes failed.\n", BLOCKSIZE);
    exit(1);
  }
  
  // 尝试分配另外一个内存块
  ptr2 = malloc(BLOCKSIZE);
  if(ptr2 != NULL){
    printf("\nSecond allocation of %d bytes successful.", BLOCKSIZE);
    exit(0);
  }
  
  //若是失败,释放第一个内存块并尝试再次分配。
  printf("\nSecond attempt to allocate %d bytes failed.", BLOCKSIZE);
  free(ptr1);
  printf("\nFreeing first block.");
  
  ptr2 = malloc(BLOCKSIZE);
  
  if(ptr2 != NULL){
    printf("\nAfter free(), allocation of %d bytes successful.\n", BLOCKSIZE);
  } 
  return (0);
}
相关文章
相关标签/搜索