Memory allocation in C

the next very simple version of malloc () and seems to give me some space, but besides the fact that there are no free (), and I do not check, I intercepted the allocated space, how can I check the correctness of the code?

Any obvious mistakes that C experts have patted me with?

#include <stdio.h>
#include <unistd.h>

#define MAX_MEMORY 1024 * 1024 * 2 /* 2MB of memory */

void *stack = NULL; /* pointer to available stack */
void * memoryAlloc(size) {
    if (stack == NULL)
        stack = sbrk(MAX_MEMORY); /* give us system memory */

    void *pointer;
    pointer = (void *)stack + size; /* we always have space :) */
    stack += size; /* move in stack forward as space allocated */
    return pointer;
}
+5
source share
3 answers

Ned Batchelder, , , . (x86) , , .

(char*) stack ( void*).

parens MAX_MEMORY. , - , , , , , . , . (, , , [] 2, MAX_MEMORY, MAX_MEMORY[arrayname], ).

, .

, , , (, 8- ):

/* Note: the following is untested                   */
/*       it includes changes suggested by Batchelder */

#include <stdio.h>
#include <unistd.h>

enum {
    kMaxMemory = 1024 * 1024 * 2, /* 2MB of memory */
    kAlignment = 8
};

void *stack = NULL; /* pointer to available stack */
void * memoryAlloc( size_t size) {
    void *pointer;

    size = (size + kAlignment - 1) & ~(kAlignment - 1);   /* round size up so allocations stay aligned */

    if (stack == NULL)
    stack = sbrk(kMaxMemory); /* give us system memory */

    pointer = stack; /* we always have space :) */
    stack = (char*) stack + size;   /* move in stack forward as space allocated */
    return pointer;
}
+11

:

  • pointer , C.

  • stack+size, , stack. . , size , . , , .

  • stack += size, stack size , size void *, .

+6

-, , , C99, C89/90. , C99.

-, K & R- ( ), . , " int", C99. , C99. "" . ( , unsigned " ". size_t - , ).

-, void *, C89/90, C99. , :)

, , , .

+2
source

All Articles