在main()或任何其他功能(即全球范围)之外的Malloc

时间:2015-11-17 21:46:39

标签: c++ class malloc variable-declaration

我想要一个类共用的堆分配缓冲区(在计算过程中用作暂存器)。在某些时候,我可以释放,然后重新分配缓冲区,如果它不够大。我希望缓冲区存在而不必调用" myclass :: initialize();"在main();我提出了以下代码,这些代码可以编译并且可以很好地用于我的目的。

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

使用" g ++ example.cpp"在linux 64bit上编译的代码并用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
}

感谢您的回答。这样的声音比我想象的更常见。 &#34;在静态初始化器中允许函数调用&#34;。这导致我稍微修改了一个版本来捕捉可能的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
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

main()只是另一个功能 - 这就是为什么它有这样的特殊要求,以允许它被正确调用。

其他事情可以而且确实在被调用之前发生。它们之间的静态初始化。