gpt4 book ai didi

c++ - Malloc 在 main() 或任何其他函数之外(即在全局范围内)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:34 27 4
gpt4 key购买 nike

我想要一个类共有的堆分配缓冲区(在计算期间用作暂存器)。在某些时候,如果缓冲区不够大,我可能会释放然后重新分配缓冲区。我希望缓冲区存在而不必调用“myclass::initialize();”在主要();我想出了以下代码,可以编译并适用于我的目的。

我的问题是:为什么这段代码可以正确编译?为什么 malloc() 允许在 main() 或任何其他函数之外?编译器是否以某种方式解释它并删除 malloc?

使用“g++ example.cpp”在 64 位 linux 上编译代码并使用 valgrind 检查

// example.cpp
#include <cstdio>
#include <cstdlib>

class myclass {
public:
static char* pbuf; // buffer
static unsigned int length; // buffer length
const static unsigned int chunk_size; // allocation chunck size
};

// set constants and allocate buffer
const unsigned int myclass::chunk_size = sizeof(long unsigned int) * 8;
unsigned int myclass::length = chunk_size; // start with smallest chunk
char* myclass::pbuf = (char*)malloc(sizeof(char)*myclass::length);

int main() {

// write to buffer (0 to 63 on 64bit machine)
for (int i = 0; i < myclass::length; i++) {
*(myclass::pbuf+i) = i;
}

// read from buffer (print the numbers 0 to 63)
for (int i = 0; i < myclass::length; i++) {
printf("%d\n", *(myclass::pbuf+i));
}

free(myclass::pbuf); // last line of program
}

感谢您的回答。听起来这比我想象的更普遍。 “静态初始值设定项中允许函数调用”。这使我得到了一个稍微修改过的版本,它捕获了一个可能的 malloc 错误:

#include <cstdio>
#include <cstdlib>

class myclass {
public:
static char* pbuf; // buffer
static unsigned int length; // buffer length
const static unsigned int chunk_size; // allocation chunck size
static void* malloc_buf(unsigned int);
};

// set constants and allocate buffer
const unsigned int myclass::chunk_size = sizeof(long unsigned int) * 8;
unsigned int myclass::length = chunk_size; // start with smallest chunk
//char* myclass::pbuf = (char*)malloc(sizeof(char)*myclass::length);
char* myclass::pbuf = (char*)myclass::malloc_buf(sizeof(char)*myclass::length);

void* myclass::malloc_buf(unsigned int N) {
void* buf = malloc(N);
if (!buf) exit(EXIT_FAILURE);
return buf;
}

int main() {

// write to buffer (0 to 63 on 64bit machine)
for (int i = 0; i < myclass::length; i++) {
*(myclass::pbuf+i) = i;
}

// read from buffer (print the numbers 0 to 63)
for (int i = 0; i < myclass::length; i++) {
printf("%d\n", *(myclass::pbuf+i));
}

free(myclass::pbuf); // last line of program
}

最佳答案

它只是在做静态初始化(调用 main 之前的初始化)。允许静态初始化程序调用函数。

关于c++ - Malloc 在 main() 或任何其他函数之外(即在全局范围内),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com