考虑一个多次调用malloc()
和free()
的应用程序.例如,该应用程序总共分配malloc()
0字节.
我正在try 编写一段代码,通过分割一个大的错误锁定内存,然后释放它来减少malloc
/free
调用的数量:
#include <stdio.h>
#include <stdlib.h>
struct A
{
char *s;
int data;
};
struct B
{
float len;
char net;
int data[];
};
struct C
{
float len;
char net;
int data[10];
struct B *b;
};
int main() {
int s =0;
char *p = malloc(1000);
char *mem = p;
//Alocate for struct A from above pool
struct A *a = (struct A *)p;
p += sizeof(struct A);
struct B *b = (struct B *)p ;
p += sizeof(struct B) + sizeof(int) * 3; //data[0]..data[2]
struct C *c = (struct C *)p;
free(mem);
return 0;
}
对于我的问题,这是合法的方法吗?我的代码或场景中是否有任何我遗漏并可能导致问题的缺陷?