0

I have following code from an object-oriented programming C book:

{
  struct Set { int count; };

  struct Set * set =  malloc(sizeof(struct Set));
  void * p = set;

  const size_t size = * (const size_t *) p;
}

I cant understand how and why last line works. size_t size is dereferenced value of pointer of type size_t. pointer of type type_t is cast from void* p. What is happening when I cast void* to type_t*, I could not find any information in the book or online tutorials. Can someone explain it to me or refer me to a good tutorial?

Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71
user3597496
  • 180
  • 1
  • 9

3 Answers3

1

So what happens here is the following: You have a pointer to a structure (p) and you cast it to a const size_t * pointer, and use the value resulted. Supposedly the value should be the same as the value of p->count however do not really count on this. According to Can I trust sizeof(size_t) <= sizeof(unsigned long int) is always true? int and size_t must not have the same size, so you well might end up with accessing memory which is not yours.

Community
  • 1
  • 1
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
  • The link you point to says that size_t will not necessarily be the same size as a long int, but that it " implicitly restricts size_t to be a synonym for an existing unsigned integer type", which is the same size as an int – David Sykes Sep 10 '14 at 07:48
  • OK thank you i finally understood. The code is depending on that struct Set contains single int. I thought that in the last line some magic happends and size contains always the size of struct Set nomatter how big that struct is. – user3597496 Sep 10 '14 at 08:03
0

Here, the void * p is being casted to const size_t * type and used as the initializer for the const size_t size variable. The value in the address [of type const size_t ]held by p is being used.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

When you cast void* p to size_t* p you are telling the compiler that p is pointing to a value of type size_t

In fact p is pointing to a a Set structure, which happens to contain a single int. The code is assuming that the type size_t is the same size as int, which the standard seems to suggest it will be

However size_t is unsigned, so if the value in the int is negative it will not be read correctly. Currently the data in the Set structure is uninitialised, so the result will be random

Community
  • 1
  • 1
David Sykes
  • 48,469
  • 17
  • 71
  • 80