You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cbmc/codedetect/tests/test_data/c_files/pointer_operations.c

135 lines
2.6 KiB

/*
* 指针操作测试文件
* 用于测试LLM生成的指针操作验证规范
*/
#include <stddef.h>
// 使用指针交换两个整数值
void swap(int *a, int *b) {
if (a == NULL || b == NULL) {
return;
}
int temp = *a;
*a = *b;
*b = temp;
}
// 指针算术操作 - 计算数组元素和
int sum_array(int *array, int size) {
if (array == NULL || size <= 0) {
return 0;
}
int sum = 0;
for (int i = 0; i < size; i++) {
sum += array[i];
}
return sum;
}
// 查找数组中的最大值
int find_max(int *array, int size) {
if (array == NULL || size <= 0) {
return 0;
}
int max = array[0];
for (int i = 1; i < size; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
// 指针递增操作
void increment_all(int *array, int size, int increment) {
if (array == NULL || size <= 0) {
return;
}
for (int i = 0; i < size; i++) {
array[i] += increment;
}
}
// 指针比较操作
int count_occurrences(int *array, int size, int target) {
if (array == NULL || size <= 0) {
return 0;
}
int count = 0;
for (int i = 0; i < size; i++) {
if (array[i] == target) {
count++;
}
}
return count;
}
// 双指针操作
void reverse_array(int *array, int size) {
if (array == NULL || size <= 1) {
return;
}
int *left = array;
int *right = array + size - 1;
while (left < right) {
int temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
// 指针参数验证
int safe_pointer_read(const int *ptr, int *result) {
if (ptr == NULL || result == NULL) {
return -1; // 错误代码
}
*result = *ptr;
return 0; // 成功代码
}
// 指针偏移操作
int* get_element_ptr(int *array, int size, int index) {
if (array == NULL || index < 0 || index >= size) {
return NULL;
}
return array + index;
}
// 指针范围检查
int is_valid_range(const int *start, const int *end, const int *ptr) {
if (start == NULL || end == NULL || ptr == NULL) {
return 0;
}
return (ptr >= start && ptr <= end);
}
// 指针复制操作
int copy_with_validation(int *dest, const int *src, int size) {
if (dest == NULL || src == NULL || size <= 0) {
return -1;
}
// 检查内存重叠
if ((src < dest && src + size > dest) || (dest < src && dest + size > src)) {
return -2; // 内存重叠错误
}
for (int i = 0; i < size; i++) {
dest[i] = src[i];
}
return 0;
}