小编nii*_*iic的帖子

从哪里调用malloc是否重要?- C

当我改变我调用malloc的函数中的位置时,我遇到了分段错误.此代码工作正常并打印"结束\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;
}
Run Code Online (Sandbox Code Playgroud)

然而,这个看似等效的代码在"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); …
Run Code Online (Sandbox Code Playgroud)

c malloc segmentation-fault

0
推荐指数
1
解决办法
77
查看次数

标签 统计

c ×1

malloc ×1

segmentation-fault ×1