保证堆栈崩溃

  • 本文关键字:崩溃 堆栈 malloc
  • 更新时间 :
  • 英文 :


我正试图使一种方法(proc将保证swap将崩溃,当一个未初始化的指针反向引用。

我想要的是,当没有分配内存时,程序崩溃。

#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("%dn", a);
    printf("%dn", b);
}

变量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 = %pn", temp);
}
int main() {
    int a = 99999;
    int b = -0;
    int c = 0;
    proc(&a, &b);
    swap(&a, &b);
    printf("%dn", a);
    printf("%dn", b);
}

proc函数应该与swap具有完全相同的堆栈布局。因此,在程序调用swap之前,它应该清除temp指针,这可能会导致这一行的交换崩溃。

但是,您可能需要禁用优化才能使其工作

最新更新