gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:44 25 4
gpt4 key购买 nike

我正在尝试为一些整数动态分配内存,但遇到了段错误。这段代码在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com