Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Correcting for scaling; now calculating elements like the text says

...

Code Block
bgColor#ffcccc
langc
#include <stddef.h>
 
enum { SIZE = 32 };
 
void func(void) {
  int nums[SIZE];
  int end;
  int *next_num_ptr = nums;
  size_t free_byteselements;

  /* Increment next_num_ptr as array fills */

  free_byteselements = &end - next_num_ptr;
}

This program incorrectly assumes that the nums array is adjacent to the end variable in memory. A compiler is permitted to insert padding bits between these two variables, or even reorder them in memory.

...

Code Block
bgColor#ccccff
langc
#include <stddef.h>
enum { SIZE = 32 };
 
void func(void) {
  int nums[SIZE];
  int *next_num_ptr = nums;
  size_t free_byteselements;

  /* Increment next_num_ptr as array fills */

  free_byteselements = (&(nums[SIZE]) - next_num_ptr) * sizeof(int);
}

Exceptions

ARR36-EX1: Comparing two pointers within the same object is allowed.
ARR36-EX2: Subtracting two pointers to char within the same object is allowed.  

...