C ++ memory allocation and linked list implementation

I am writing software to simulate a “first fit” memory allocation scheme.

Basically, I allocate a large X megabyte chunk of memory and subdivide it into blocks when chunks are requested in accordance with the scheme.

I use a linked list called "node" as a header for each memory block (so that we can find the next block without a tedious loop through each address value.

head_ptr = (char*) malloc(total_size + sizeof(node));

if(head_ptr == NULL) return -1; // Malloc Error .. :-(

node* head_node = new node; // Build block header

head_node->next = NULL;
head_node->previous = NULL;

// Header points to next block (which doesn't exist yet)
memset(head_ptr,head_node, sizeof(node));

`

But this last line returns:

 error: invalid conversion from 'node*' to 'int'

I understand why this is not true. But how can I put my node at the pointer location of my newly allocated memory?

+3
source share
4 answers
memset(void* memory, int value, size_t size)

, head_node head_ptr ( memcpy), ( 0, ..).

head_ptr node*:

node* head_node = (node*)head_ptr;

delete head_node, head_ptr .

+2

. memset int ( unsigned char) . n , n .

memcpy, . :

memcpy(head_ptr, head_node, sizeof(node));

EDIT: head_ptr , .

+1

, node head_ptr. node, , :

node* head_node = new(head_ptr) node;

, , delete:

head_node->~node();
+1

. int .

memset(3):

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

DESCRIPTION
     The memset() function writes len bytes of value c (converted to
     an unsigned char) to the byte string b.

RETURN VALUES
     The memset () function returns its first argument.
0
source

Source: https://habr.com/ru/post/1739235/


All Articles