How to make block bytes initialized so that they contain all 0s

I am writing a function callocin a memory management assignment (I am using C). I have one question: I have written a function mallocand was thinking of using it for calloc, as he says he callocwill take numand sizeand return a block of memory (num * size)that I can use mallocto create, however, he says that I need to initialize all the bytes to 0 , and I'm confused about how to do this in general? If you need more information, ask me :)

So, it mallocwill return the pointer (Void pointer) to the first of the used memory, and I have to go through the bytes, initialize them to zero and return the pointer to this edge of the useful memory.

+3
source share
4 answers

I assume that you cannot use memsetit because it is the assignment of homework tasks and deals with memory management. So, I would just go into a loop and set all the bytes to 0. Pseudocode:

for i = 1 to n:
   data[i] = 0

Oh, if it's hard for you to figure out how to play void *, remember what you can do:

void *b;
/* now make b point to somewhere useful */
unsigned char *a = b;
+4
source

If you need to set the memory block to the same value, use the function memset.

It looks like this: void * memset ( void * ptr, int value, size_t num );

: http://www.cplusplus.com/reference/clibrary/cstring/memset/

+2

memset, .

malloc calloc, , :

void *calloc (size_t count, size_t sz) {
    size_t realsz = count * sz;
    void *block = malloc (realsz);
    if (block != NULL) {
        // Zero memory here.
    }
    return block;
}

"// Zero memory here.".

.

  • , , (char ). () int, int *block2 = (int*)block;.

  • , . , , , .

, , , . , , , ( , ).

. , . calloc malloc:

void *calloc (size_t count, size_t sz) {
    size_t realsz, i;
    char *cblock;

    // Get size to allocate (detect size_t overflow as well).

    realsz = count * sz;
    if (count != 0)
        if (realsz / count != sz)
            return NULL;

    // Allocate the block.

    cblock = malloc (realsz);

    // Initialize all elements to zero (if allocation worked).

    if (cblock != NULL) {
        for (i = 0; i < realsz; i++)
            cblock[i] = 0;
    }

    // Return allocated, cleared block.

    return cblock;
}

, char , void.

+1

:

  • posix

  • consider using void *a pointer of some kind that you can dereference / assign.

0
source

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


All Articles