官术网_书友最值得收藏!

Memory management

All of the memory management functions that libc provides are considered POSIX APIs as well. In addition, there are some POSIX-specific memory management functions that libc doesn't provide, such as aligned memory.

For example, the following demonstrates how to allocate aligned dynamic (heap) memory using POSIX:

#include <iostream>

int main()
{
void *ptr;

if (posix_memalign(&ptr, 0x1000, 42 * sizeof(int))) {
std::clog << "ERROR: unable to allocate aligned memory\n";
::exit(EXIT_FAILURE);
}

std::cout << ptr << '\n';
free(ptr);
}

// > g++ -std=c++17 scratchpad.cpp; ./a.out
// 0x55c5d31d1000

In this example, we use the posix_memalign() function to allocate an array of 42 integers, which is aligned to a page. This is a POSIX-specific function.

In addition, we leverage the std::clog() function to output an error to stderr, which, under the hood, leverages POSIX-specific functions for outputting character strings to stderr. We also use ::exit(), which is a libc and POSIX function for exiting an application.

Finally, we leverage both the std::cout() and free() functions. std::cout() uses POSIX functions to output character strings to stdout, while free() is both a libc and POSIX-specific function for freeing up memory. 

In this simple example, we are leveraging several C, C++, and POSIX-specific functionalities to perform system programming. Throughout this book, we will discuss how to leverage POSIX heavily to program the system to accomplish specific tasks.

主站蜘蛛池模板: 吕梁市| 荆门市| 桂平市| 翁牛特旗| 通城县| 谢通门县| 犍为县| 孝义市| 丹凤县| 云霄县| 永年县| 南木林县| 平原县| 昌江| 永胜县| 泾阳县| 绥德县| 阆中市| 五家渠市| 冕宁县| 扎赉特旗| 临桂县| 襄汾县| 合川市| 阜新| 冀州市| 南江县| 赤峰市| 云和县| 黎川县| 全州县| 泌阳县| 巫溪县| 淮阳县| 平远县| 崇阳县| 荣成市| 巴彦淖尔市| 武城县| 普安县| 兴山县|