C, dynamically memory allocation

Posted sarah-zhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C, dynamically memory allocation相关的知识,希望对你有一定的参考价值。

0.

1. strcpy() function

#include <string.h>

char* strcpy(char* destination, const char* source);

 

2. Allocating Memory dynamically:

 (1) void* malloc(int num);

#include <malloc.h>

int *p = (int*)malloc(n * sizeof(int));  // cast void* to int*, and the memory is not initialized 

if (p!= NULL){ /* allocation successful */}

else {/*allocation fails*/}

free(p);  // memory leak if not free 

 

(2) void* calloc(size_t  num, size_t size);

#include <stdlib.h>

int *p = (int*)calloc(n, sizeof(int));  // total allocated bytes are n*sizeof(int) 

if (p!= NULL){ /* allocation successful */}

else {/*allocation fails*/}

free(p);  // memory leak if not free 

 

(3) void* realloc(void* ptr, size_t size); 

Change the size of the memory block pointed to by ptr;

The function may move the memory block to a new location(whose address is returned by the function)

In case that ptr is a null pointer, the function behaves like malloc()

#include <stdlib.h>

int *p = (int*)realloc(ptr, 200 * sizeof(int));  // expend the allocation to 200*sizeof(int) 

if (p!= NULL){ /* allocation successful */}

else {/*allocation fails*/}

free(p);  // memory leak if not free 

以上是关于C, dynamically memory allocation的主要内容,如果未能解决你的问题,请参考以下文章

Dynamically allocated memory 动态分配内存mallocMemory leaks 内存泄漏

dynamic_memory_allocation(动态内存分配)

Cpp Chapter 12: Classes and Dynamic Memory Allocation Part2

Cpp Chapter 12: Classes and Dynamic Memory Allocation Part1

PostgreSQL-9.6.3LOG: unrecognized configuration parameter "dynamic_shared_memory_type"((代

[Paper翻译]Scalable Lock-Free Dynamic Memory Allocation