How to store an integer value of 4 bytes in the memory of a fragment, which is divided as a type char

I allocated a chunk of memory of type char, and the size is 10 MB (i.e. mem_size = 10):

int mem_size = 10; 
char *start_ptr;
if((start_ptr= malloc(mem_size*1024*1024*sizeof(char)))==NULL) {return -1;}

Now I want to save the size information in the header of the memory block. To make myself clearer, let's say: start_ptr = 0xaf868004 (This is the value I received from my execution, it changes every time).

Now I want to put size information at the beginning of this pointer, i.e. *start_ptr = mem_size*1024*1024;.

But I can not put this information in start_ptr. I think the reason is that my ptr has a type charthat accepts only one byte, but I'm trying to save int, which takes 4 bytes, is a problem.

I am not sure how to solve this problem.

+3
source share
5 answers

You need to point charto a pointer int. In two stages:

int *start_ptr_int = (int*)start_ptr;
*start_ptr_int = mem_size * 1024 * 1024;

In one step:

*((int*)start_ptr) = mem_size * 1024 * 1024;

(int*)before the name of your pointer, it tells the compiler: "Yes, I know that this is not really a pointer to int, but just pretending at the moment, okay?"

+5
source
*((int*)start_ptr) = mem_size*1024*1024
+1
source

memcpy ...

int toCopy = mem_size * 1024 * 1024;
memcpy( start_ptr, &toCopy, 4 );

, memcpy .

+1

:

#include <stdlib.h>
struct Block {
    size_t size;
    char data[];
};
#define SIZE (1024*1024)
int main()
{
    struct Block* block = malloc(sizeof(struct Block) + SIZE);
    block->size = SIZE;
    char* start_ptr = block->data;
    // ...
}

, , :

char* start_ptr = (char*)block;
+1

: :

if ((ptr=malloc()) == NULL)

ptr = malloc();
if (ptr == NULL) ...

, . , .;)

And -1 for all posters that assume that int in C will always be 32 bits, including OP in the thread header. It is assumed that int has at least 16 bits, and on 32-bit machines the usually safe assumption is 32 bits, but your code may fail as soon as you switch to a 64-bit machine.

0
source

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


All Articles