c - Can I do what I want with allocated memory -


are there limits on can allocated memory?(standard-wise)

for example

#include <stdio.h> #include <stdlib.h>  struct str{     long long a;     long b; };  int main(void)  {     long *x = calloc(4,sizeof(long));     x[0] = 2;     x[3] = 7; //is beyond here legal( if exclude possible illegal operations)     long long *y = x;      printf("%lld\n",y[0]);      y[0] = 2;     memset (x,0,16);     struct str *bar = x;     bar->b =  4;     printf("%lld\n",bar->a);      return 0; } 

to summarize:

  • can recast pointer other datatypes , structs, long size fits?
  • can read before write, then?
  • if not can read after wrote?
  • can use struct smaller allocated memory?

reading y[0] violates strict aliasing rule. use lvalue of type long long read objects of effective type long.

assuming omit line; next troublesome part memset(x,0,16);. this answer argues memset not update effective type. standard not clear.

assuming memset leaves effective type unchanged; next issue read of bar->a.

the c standard unclear on too. people bar->a implies (*bar).a , strict aliasing violation because did not write bar object location first.

others (including me) fine: lvalue used access bar->a; lvalue of type long long, , accesses object of effective type long long (the 1 written y[0] = 2;).

there c2x working group working on improving specification of strict aliasing clarify these issues.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -