- Hands-On System Programming with C++
- Dr. Rian Quinn
- 209字
- 2021-07-02 14:42:35
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.
- 數(shù)據(jù)庫(kù)基礎(chǔ)教程(SQL Server平臺(tái))
- Microsoft SQL Server企業(yè)級(jí)平臺(tái)管理實(shí)踐
- Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn)
- Python廣告數(shù)據(jù)挖掘與分析實(shí)戰(zhàn)
- 淘寶、天貓電商數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第2版)
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- The Natural Language Processing Workshop
- 數(shù)據(jù)指標(biāo)體系:構(gòu)建方法與應(yīng)用實(shí)踐
- 區(qū)塊鏈應(yīng)用開(kāi)發(fā)指南:業(yè)務(wù)場(chǎng)景剖析與實(shí)戰(zhàn)
- 大數(shù)據(jù)隱私保護(hù)技術(shù)與治理機(jī)制研究
- 基于數(shù)據(jù)發(fā)布的隱私保護(hù)模型研究
- 數(shù)字孿生
- 數(shù)據(jù)可視化五部曲
- 產(chǎn)品經(jīng)理數(shù)據(jù)修煉30問(wèn)
- 數(shù)據(jù)質(zhì)量管理:數(shù)據(jù)可靠性與數(shù)據(jù)質(zhì)量問(wèn)題解決之道