How to manage memory alignments and typical pointer arithmetic in a portable way in C?

I need to implement an optimized version of malloc / realloc / free (specifically for my specific application). The code currently runs on a specific platform, but I would like to write it in a portable way, if possible (the platform may change in the future), or at least I would like to concentrate the possible differences in the platform in one (probably .h ) I know about some issues:

  • differences in memory alignment
  • differences in the smallest sizes of memory blocks suitable for a "shared" distribution
  • differences in pointer size

(I will ignore the differences in the basic system services for memory allocation here, since on some embedded systems they may not be available at all. Imagine that we are working on a large pre-allocated memory block that will be used as a heap,).

Question (s):

  • Are there standard macros or functions in C for this purpose?
  • What other problems may arise in this work?
+5
source share
6 answers

C, C11. _Alignof, _Alignas aligned_alloc. ( ), , __STDC_VERSION__.

+1

, , , - :

union alloc_align {
    void *dummy1;
    long long dummy2;
    long double dummy3;
};

... , , , sizeof (union alloc_align) , .

, K & R.

+3

( ), MSVC aligned_malloc, POSIX memalign Linux, _mm_alloc, ICC, MSVC GCC, IIRC, .

- , , - -, .

, (, SIMD), __attribute__((__aligned__(x))) __declspec(align(x)).

stdint.h/pstdint.h, , - UB uintptr_t ( , aren ' t :().

+1

, malloc() , - . , , sizeof , n, , :

p = malloc(sizeof(*p) * n);

, , s = 4 n = 10, s = 2 n = 20 s = 1 n = 40, 40 .

, , , . . , s n.

void *my_malloc (size_t s, size_t n)

, s, .

, malloc() (, 16), .

+1

#pragma, , .

0

C , malloc , . C , C. , malloc - , , C, .

(C99, 7.20.3p1) " , , , ( ).

0
source

All Articles