为什么的malloc(sizeof的(指针))工作? [英] why does malloc(sizeof(pointer)) work?

查看:240
本文介绍了为什么的malloc(sizeof的(指针))工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这下code正常工作:

This following code works fine:

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

int main()
{
    struct node{
        int a, b, c, d, e;
    };
    struct node *ptr = NULL;
    printf("Size of pointer ptr is %lu bytes\n",sizeof (ptr));
    printf("Size of struct node is %lu bytes\n",sizeof (struct node));
    ptr = (struct node*)malloc(sizeof (ptr));               //Line 1
//    ptr = (struct node*)malloc(sizeof (struct node));    //Line 2

    ptr->a = 1; ptr->b = 2; ptr->c = 3; ptr->d = 4; ptr->e = 5;
    printf("a: %d, b: %d, c: %d, d: %d, e: %d\n",
            ptr->a,ptr->b,ptr->c,ptr->d,ptr->e);
    return 0;
}

在遵从为:

gcc -Wall file.c

我的问题是:为什么是这样的好

My question is: why is this fine?

的malloc 分配被指定在它的参数的字节数。在这里, sizeof的PTR 是我的64位Linux机器上的8个字节。我以为的malloc 将提供8个字节但它是如何访问所有的变量A,B,C,D,E?它是用gcc只能还是我失去了标准C的东西吗?

malloc allocates the number of bytes which are specified in it's argument. Here sizeof ptr is 8 bytes on my 64-bit linux machine. I thought malloc will provide 8 bytes but then how is it accessing all the variables a,b,c,d,e? Is it with gcc only or am I missing something with standard C?

据我所知,2号线应该在那里,而不是1号线,但无论是线路的正常工作。为什么呢?

As far as I know "Line 2" should be there instead of "Line 1" but either of the line works fine. Why?

推荐答案

您不确定这里的行为。

的malloc 将分配8个字节(如你所说),但这种转换是坏:

malloc will allocate 8 bytes (as you say), but this cast is "bad":

ptr = (struct node*)malloc(sizeof (ptr));

这行之后, PTR 将指向一个内存块,它只有8个字节分配,剩下的都是一些随机的字节。因此,使得

After this line, ptr will point to a memory block, which has only 8 allocated bytes, the rest are some "random" bytes. So, making

ptr->a = 1; ptr->b = 2; ptr->c = 3; ptr->d = 4; ptr->e = 5;

您真正改变一些内存,不仅的malloc分配

you actually change some memory, not only the allocated by malloc.

在换句话说,你重写内存,你不应该去碰。

In other words, you are rewriting memory, you're not supposed to touch.

这篇关于为什么的malloc(sizeof的(指针))工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆