Sizeof operator in a value securely encoded in C

  • 2020-04-02 02:20:57
  • OfStack

Generally speaking Do not apply the sizeof operator to a pointer when getting the length of an array .

Here's the code:


void clear(int array[]) {
  for(size_t i = 0; i < sizeof(array) / sizeof(array[0]); i++) {
    array[i] = 0;
  }
}
void dowork(void) {
  int dis[12];
  clear(dis);
  
}

Clear () USES sizeof(array)/sizeof(array[0]) to determine the number of elements in the array, but since array is a parameter, it is a pointer type, sizeof(array) = sizeof(int *) = 4   (32-bit OS)

When the sizeof operator is applied to a parameter declared as an array or function type, it produces an adjusted length of the type

The solution to this problem is as follows:


void clear(int array[], size_t len) {
  for(size_t i = 0; i < len; i++) {
    array[i] = 0;
  }
}
void dowork(void) {
  int dis[12];
  clear(dis, sizeof(dis) / sizeof(dis[0]));
  
}


Related articles: