简体   繁体   English

使用malloc时堆与堆栈内存

[英]heap vs stack memory while using malloc

In following code: 在以下代码中:

int main(void)
{
    char* a = malloc(sizeof(char));
    a[0] = 'a';
    a[1] = 'b';
    a[2] = 'c';
    printf("%s", a);
}

Acc. 加。 to me a[0] is being allocated memory from heap while a[1] and a[2] are on the stack. 对我来说,a [0]正在从堆分配内存,而a [1]和a [2]在堆栈中。 I get the output of following code as abc . 我得到以下代码的输出为abc How is that happening, if stack and heap are supposed to two different segments of memory I must get only a as the output as I have allocated memory in heap for only one char. 这是怎么回事,如果应该将堆栈和堆分配到两个不同的内存段,那么我必须仅获得a作为输出,因为我只为一个字符分配了堆中的内存。

You're only allocating room on the heap for one char in a , but you're writing three. 你只是在堆上分配了一个房间chara ,但你写三封。 The other two don't magically go to the stack; 另外两个不会神奇地进入堆栈; they just overwrite some other probably-important value that happens to be after the one you did allocate. 它们只是覆盖了其他一些可能很重要的值,而该值恰好在您分配的值之后。 Your program is simple enough that it didn't blow up in your face, but it's still Undefined Behavior to do this. 您的程序非常简单,不会在您的面前炸死,但是执行此操作仍然是未定义行为。 C doesn't have bounds checking, so it won't save you from this mistake. C没有边界检查,因此它不会使您摆脱这个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM