0

当我更改调用 malloc 的函数中的位置时,出现分段错误。此代码工作正常并打印“End\n”。

#include <stdio.h>
#include <stdlib.h>

int main() {    

    int **pptr;
    if (!( *pptr = malloc(4) ))
        return 1;

    int *ptr;
    if (!( ptr = malloc(4) ))
        return 1;

    ptr[0]= 1;
    printf("Point 1\n");

    free(ptr);

    (*pptr)[0] = 1;

    free(*pptr);
    printf("End\n");
    return 0;
}

然而,这个看似等效的代码在分段错误的“Point 1\n”之前结束。

#include <stdio.h>
#include <stdlib.h>

int main() {    

    int *ptr;
    if (!( ptr = malloc(4) ))
        return 1;

    ptr[0]= 1;
    printf("Point 1\n");

    free(ptr);

    int **pptr;
    if (!( *pptr = malloc(4) ))
        return 1;
    (*pptr)[0] = 1;

    free(*pptr);
    printf("End\n");
    return 0;
}

我错过了什么?(我有点初学者)

其他信息:我在 Ubuntu 下使用 Netbeans,使用 gcc。

4

2 回答 2

5

在这两个程序中,您都在此处调用未定义的行为:

int **pptr;
if (!( *pptr = malloc(4) ))
    return 1;

pptr是一个未初始化的指针,它被取消引用以存储由 . 返回的指针malloc。由于未定义的行为,第一个恰好看起来像是在工作,但正在破坏pptr恰好指向的内存。

第二个失败是因为pptr恰好指向一个无法写入的内存区域。

此外,由于在上面的代码int*中分配了一个,malloc(4)因此是不安全的。使用malloc(sizeof(int*)). 例如,64 位系统通常具有 8 字节指针。

于 2013-10-05T17:48:04.680 回答
2

What is sizeof(int)? If it's > 4 then yes, you are invoking undefined behavior.

When invoking undefined behavior, yes, order can matter. Anything can matter. Whether your system time is even or odd at start of run of program can (but probably won't) matter. That's what undefined means.

In this case, I suspect the two mallocs somehow informed your compiler on what memory to allocate, and you "got lucky" in the first case in that it happened to be overwriting to writeable space. Of course in the larger scheme you got unlucky, since I suspect you failed silently.

Anyway, start by making the program correct, then figure out what your UB is, then figure out what implementation details may have caused it.

于 2013-10-05T17:43:43.583 回答