C safe array length and pointer instance resolution

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

1.C language coding needs Ensure that the length parameter of the variable-length array is in the legal range

For example, the following code:


void func(size_t s) {
 int vla[s];
 
}

func(size);


The solution is as follows:


enum {MAX_ARRAY = 1024};
void func(size_t s) {
 if(s < MAX_ARRAY && s != 0) {
  int vla[s];
  
 } else {
  //Error handling
 }
}

func(size);


Need 2. Ensure that the replication target has sufficient storage space

The reference code is as follows:


enum {WORKSPACE_SIZE = 256};
void func(const int src[], size_t len) {
 int dest[WORKSPACE_SIZE];
 if(len > WORKSPACE_SIZE) {
  //Error handling
 }
 memcpy(dest, src, sizeof(int) * len);
 
}

3. Do not add or subtract an integer from a pointer to a non-array object

The error code is as follows:


struct numbers {
 short num1;
 short num2;
 
 short num9;
};
int sum_numbers(const struct numbers *numb) {
 int total = 0;
 const int *numb_ptr;
 for(numb_ptr = &numb->num1; numb_ptr <= &numb->num9; numb_ptr++) {
  total += *(numb_ptr);
 }
 return total;
}
int main(void) {
 struct numbers my_numbers = {1,2,3,4,5,6,7,8,9};
 sum_numbers(&my_numbers);
 return 0;
}

The code above tries to access elements of the structure with pointer operations, which is dangerous because the fields in the structure are not guaranteed to be contiguous in memory

The solution (using arrays) is as follows:


struct numbers {
 short num1;
 short num2;
 
 short num9;
};
int sum_numbers(const short *numb, size_t dim) {
 int total = 0;
 const int *numb_ptr;
 for(numb_ptr = numb; numb_ptr < numb + dim; numb_ptr++) {
  total += *(numb_ptr);
 }
 return total;
}
int main(void) {
 short my_numbers[9] = {1,2,3,4,5,6,7,8,9};
 sum_numbers(my_numbers, sizeof(my_numbers) / sizeof(my_numbers[0]));
 return 0;
}

Related articles: