检查数组越界等

 

1、如何定位全局数组的写越界,一个被大量引用的全局数组int a[100],被写越界了,这样的情况如何定位?
 最简单的方法是,将数组a[100]改为a[101],然后对访问a[100]的地方设置断点进行调试。因为a[100]应该是没有人访问

的,如果访问就是越界访问,直接可以定位到该位置。

2、在linux下防止某个程序被运行两次的方法

通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利

用open语句创建该文件,程序退出时关闭并删除此文件。

具体代码:

static char file_lock[sizeof(ctl_addr.sun_path)] = /var/run/file.pid;
static bool file_lock_created = FALSE;

static int
create_lock(void)
{
 int fd = open(file_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
 S_IRUSR | S_IRGRP | S_IROTH);

 if (fd < 0)
 {
 if (errno == EEXIST)
 {
 fprintf(stderr, "file: lock file "%s" already existsn", file_lock);
 exit_file(10);
 }
 else
 {
 fprintf(stderr, "file: unable to create lock file "%s" (%d %s)n"
 , file_lock, errno, strerror(errno));
 exit_file(1);
 }
 }
 file_lock_created = TRUE;
 return fd;
}

static bool
fill_lock(int lockfd)
{
 char buf[30];
 pid_t pid;
 int len;

 pid = getpid();
 len = snprintf(buf, sizeof(buf), "%un", (unsigned int) pid);
 bool ok = len > 0 && write(lockfd, buf, len) == len;

 close(lockfd);
 return ok;
}

static void
delete_lock(void)
{
 if (file_lock_created)
 {
 //delete_ctl_socket();
 unlink(file_lock);
 }
}

### 使用 `assert` 进行数组越界检查 #### C++ 在 C++ 中,可以通过定义辅助函数来利用 `assert` 检查索引是否超出范围。下面展示了一个简单的例子: ```cpp #include <iostream> #include <cassert> void accessArray(int* array, size_t length, size_t index) { // 断言用于验证条件,在调试模式下如果条件不满足则终止程序并给出提示 assert(index < length && "Index out of bounds"); std::cout << "Accessing element at index " << index << ": " << array[index] << '\n'; } int main() { int myArray[] = {1, 2, 3}; size_t n = sizeof(myArray)/sizeof(*myArray); accessArray(myArray, n, 0); // 正确访问 accessArray(myArray, n, 3); // 将触发断言失败 return 0; } ``` 此代码片段展示了如何通过传递数组及其长度到一个辅助函数中,并使用 `assert` 来防止非法访问[^2]。 #### Python Python 提供了内置的 `assert` 关键字来进行类似的边界检查操作。这里有一个简单实例说明其用法: ```python def get_item(lst, idx): try: # 如果idx不在有效范围内,则抛出异常 item = lst[idx] except IndexError as e: raise AssertionError(f'Index {idx} is out of range.') from e return item if __name__ == '__main__': test_list = ['a', 'b', 'c'] print(get_item(test_list, 1)) # 输出 b print(get_item(test_list, 5)) # 抛出AssertionError: Index 5 is out of range. ``` 这段脚本尝试获取列表中的项目,当请求的索引超出了实际大小时会引发自定义的消息[^1]. #### Java Java 并不像某些其他编程语言那样直接支持 `assert`,但是自从 JDK 1.4 版本以来已经加入了这一特性。默认情况下它处于关闭状态,因此需要显式启用才能生效。下面是有关于怎样实现这一点的例子: ```java public class ArrayBoundsCheck { public static void main(String[] args) { Integer[] numbers = new Integer[]{1, 2, 3}; System.out.println(accessElement(numbers, 0)); // prints 1 System.out.println(accessElement(numbers, 3)); // triggers assertion error when run with assertions enabled (-ea flag) } private static Object accessElement(Integer[] arr, int i){ // Enable this line only during development/testing phase by running JVM with '-ea' // Otherwise it will be ignored in production environment without any effect on performance assert i >= 0 && i < arr.length : "Invalid index value"; return arr[i]; } } ``` 为了使上述代码工作正常,编译和执行该类文件时应加上 `-ea` 参数以开启断言语句的支持[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值