保证堆栈崩溃

时间:2013-03-22 22:16:50

标签: malloc

我正在尝试制作一种方法(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);
}

1 个答案:

答案 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指针,这可能会使该行发生交换崩溃。

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