HackerTrans
TopNewTrendsCommentsPastAskShowJobs

clairebyte

no profile record

comments

clairebyte
·vor 2 Jahren·discuss
If you can guarantee its always compiled in a separate TU and never inlined, sure, might be a practical way so 'solve' this issue, but if you then do some LTO (or do a unity build or something) the compiler might suddenly break your code. Another way is to add an inline asm block with "memory" clobber to escape the pointer so the optimizer can't destroy your code.

It's really quite ridiculous that compiler implementers have managed to overzealously nitpick the C standard so that you can't implement a memory allocator in C.
clairebyte
·vor 2 Jahren·discuss
>The act of writing a value of a different type tells the compiler that the lifetime of the previous object has ended.

afaik only memcpy has that magic property, so I think parent is almost correct.

  void *p = malloc(n);
  *(int *)p = 42; // ok, *p is now an int.
  //*(float *)p = 3.14f; // I think this is not allowed, p points to an int object, regular stores do not change effective type
  float x = 3.14f;
  memcpy(p, &x, sizeof(float)); // but this is fine, *p now has effective type float
So in the new, pool_new:

  pool->chunk_arr[i].next = &pool->chunk_arr[i + 1];
This sets the effect type of the chunk block to 'Chunk'

Later in pool_alloc:

  Chunk* result    = pool->free_chunk;
  ...
  return result;
result has effective type 'Chunk'

In user code:

  int *x = pool_alloc();
  *x = 42; // aliasing violation, *x has effective type 'Chunk' but tried to access it as an int*
User code would need to look like this:

  int *x = pool_alloc();
  memcpy(x, &(int){0}, sizeof(int)); // establish new effective type as 'int'
  // now we can do
  *x = 42;**