Here is an example of continuous memory allocation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <type.h>
#define HASH_MAXSIZE 193
#define HASH_NODE_MAXSIZE 65535
struct code_info
{
char infos[256];
uint8_t code;
};
struct hash_node
{
struct code_info* infos;
struct hash_node* next;
};
struct hash_table
{
struct hash_node* table;
};
struct myobject
{
struct hash_table* code_table;
struct hash_node* node_buffer;
struct code_info* info_buffer;
};
int main(int argc, char** argv)
{
struct myobject * my = (struct myobject*)malloc(sizeof(struct myobject));
// an error may occur in allocating memeory
my->code_table = (struct hash_table*)malloc(HASH_MAXSIZE * sizeof(struct hash_table));
// an error may occur in allocating memeory
my->node_buffer = (struct hash_node*)malloc(HASH_NODE_MAXSIZE * sizeof(struct hash_node));
// an error may occur in allocating memeory
my->info_buufer = (struct code_info*)malloc(HASH_NODE_MAXSIZE * sizeof(struct code_info));
// an error may occur in allocating memory
return 0;
}
I learned that when a memory allocation failure occurs, it is not only necessary to prompt an error message and return it, but also to free up the allocated memory space. But there are too many memory allocation places, each memory allocation need to use conditional statements to judge and then prompt and release the allocated memory? Code is not concise enough!
Is there any good way to solve this problem? thank you!