我正在尝试制作一种方法(proc
)
将保证在未初始化指针时交换将崩溃
解除引用。
我想要的是,当没有分配内存时,程序会崩溃。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void swap (int *px, int *py) {
int *temp;
*temp = *px; // Why doesn't this crash?
*px = *py;
*py = *temp;
}
int main() {
int a = 99999;
int b = -0;
int c = 0;
//proc(/* Some args might go here */);
swap(&a, &b);
printf("%d\n", a);
printf("%d\n", b);
}
答案 0 :(得分:0)
变量temp
在堆栈上分配,因此当程序到达行*temp = *px;
时,它可能已包含一些有效指针。在这种情况下,即使您没有初始化程序,程序也不会崩溃。您可以使用gdb对其进行调试,在此行中断并键入p temp
以查看值是否存储在其中。
但是,如果你真的希望程序崩溃。请尝试以下方法:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void swap (int *px, int *py) {
int *temp;
*temp = *px; // Why doesn't this crash?
*px = *py;
*py = *temp;
}
void proc(int *px, int *py) {
int *temp = 0;
printf("temp = %p\n", temp);
}
int main() {
int a = 99999;
int b = -0;
int c = 0;
proc(&a, &b);
swap(&a, &b);
printf("%d\n", a);
printf("%d\n", b);
}
proc
函数应与swap
具有完全相同的堆栈布局。所以它应该在程序调用{{1}}之前清除temp
指针,这可能会使该行发生交换崩溃。
但是,您可能需要禁用优化才能使其正常工作。