c - 为什么这个 malloc 会在我的虚拟机上导致段错误?

标签 c int malloc ubuntu-16.04

我正在尝试为一些整数动态分配内存,但遇到了段错误。这段代码在 native MacOS 上运行良好,但是当我尝试在我的 Ubuntu 虚拟机上运行它时却失败了?有什么区别?

代码

// Create stuff to add
int* a = malloc(sizeof(int));
int* b = malloc(sizeof(int));
int* c = malloc(sizeof(int));
int* d = malloc(sizeof(int));
*a = 0;
*b = 1;
*c = 2;
*d = 3;

错误

Breakpoint 1, test_add_4_and_check () at test.c:125
125     int* a = malloc(sizeof(int));
(gdb) n
126     int* b = malloc(sizeof(int));
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a8b48a in malloc_consolidate (
    av=av@entry=0x7ffff7dd1b20 <main_arena>) at malloc.c:4175
4175    malloc.c: No such file or directory.

最佳答案

您没有验证 malloc 没有失败:

int *a = malloc(sizeof *a);
int *b = malloc(sizeof *b);
int *c = malloc(sizeof *c);
int *d = malloc(sizeof *d);
if (!a || !b || !c || !d) {
  exit(EXIT_FAILURE);
}
*a = 0;
*b = 1;
*c = 2;
*d = 3;

我想虚拟机可能没有足够的内存。


完整代码:

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

int main(void) {
    int *a = malloc(sizeof *a);
    if (!a) {
        fprintf(stderr, "a allocation fail\n");
        goto a;
    }
    int *b = malloc(sizeof *b);
    if (!b) {
        fprintf(stderr, "b allocation fail\n");
        goto b;
    }
    int *c = malloc(sizeof *c);
    if (!c) {
        fprintf(stderr, "c allocation fail\n");
        goto c;
    }
    int *d = malloc(sizeof *d);
    if (!d) {
        fprintf(stderr, "d allocation fail\n");
        goto d;
    }

    *a = 0;
    *b = 1;
    *c = 2;
    *d = 3;

    free(d);
    free(c);
    free(b);
    free(a);

    return EXIT_SUCCESS;

d:
    free(c);
c:
    free(b);
b:
    free(a);
a:
    return EXIT_FAILURE;
}

关于c - 为什么这个 malloc 会在我的虚拟机上导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49820508/

相关文章:

在标准 C 中将 int 转换为 char*(无 itoa)

c - 如何在 C 中使用 malloc() 分配结构数组?

c - 读取二进制文件,存入缓冲区,打印缓冲区内容

CORDIC 反正弦实现失败

编译执行Redis ziplist.c

c# - 连接多个整数以形成更大的整数

python - 如何仅对列表的 int 部分执行操作?

c - 动态 C 字符串 (char*) 奇怪的行为

c - C 中的 fopen 出现段错误? (不太确定导致错误的原因)

C - 特定天数是多少小时?