简体   繁体   English

有人可以解释一下我在使用malloc作为指针时发生了什么

[英]can someone explain me what is happening here for using malloc for pointer

#include<stdio.h>
int main(){
    int * ptr=(int *)malloc(40);
    printf("%d",sizeof(ptr));
}

When I'm running this, output is coming as 8...what is happening here...why is output 8? 当我运行此命令时,输出为8 ...这里发生了什么...为什么输出8?

The sizeof operator is a compile time operator, and the size of any pointer is 8 bytes on your machine. sizeof运算符是编译sizeof算符,计算机上任何指针的大小均为8字节。

There is no way to retrieve the dynamic size of the malloc -ed memory zone. 没有办法检索由malloc分配的内存区域的动态大小。 You have to know it otherwise, or to keep it somewhere. 否则,您必须知道它,或者将其保存在某个地方。

You might consider using Boehm's conservative garbage collector then you'll call GC_malloc instead of malloc , you won't need to call free (or GC_free ), and you could use GC_size(p) to get the approximate size of the previously GC_malloc -ed memory zone starting at p (but I don't recommend using GC_size ). 您可能会考虑使用Boehm的保守性垃圾收集器,然后将调用GC_malloc而不是malloc ,而无需调用free (或GC_free ),并且可以使用GC_size(p)来获取以前的GC_malloc -ed的近似大小。从p开始的内存区域(但我不建议使用GC_size )。

If using malloc on Linux, learn how to use valgrind to hunt memory leak bugs, and compile with gcc -Wall -g 如果在Linux上使用malloc ,请学习如何使用valgrind来发现内存泄漏错误,并使用gcc -Wall -g编译

malloc() returns a pointer to 40 bytes of memory (probably 10 ints) and assigns it to ptr . malloc()返回指向40字节内存(可能为10 ints)的指针,并将其分配给ptr The reason sizeof(ptr) is 8 is because you are using a 64 bit machine and pointers are 8 bytes in size. sizeof(ptr)为8的原因是因为您使用的是64位计算机,并且指针的大小为8个字节。

You should use sizeof() inside the malloc() because it's good form and avoids problems if the type ever changes size (crossing platforms or whatever). 您应该在malloc() sizeof()内部使用sizeof() ,因为它是一种很好的形式,并且可以避免类型改变大小(跨平台或其他)的问题。 If you really want space for 10 ints then use: 如果您确实想要10个整数的空间,请使用:

int *ptr = malloc(10 * sizeof *ptr);

This allocates 10 lots of the size of the type ptr points to, in this case int . 这将分配10个ptr点类型的大小,在本例中为int The benefit of doing this is you can change the type without changing the malloc() 这样做的好处是您可以更改类型而无需更改malloc()

变量ptr是一个指向int的指针,在您的系统中,它恰好具有8个字节的大小。

ptr is a pointer.its printing the size fo the pointer on your system. ptr是一个指针。它在系统上打印指针大小。 as ptr holds an address, 8 bytes is the size required to hold an address on a 64 bit machine. 由于ptr拥有一个地址,因此在64位计算机上保留一个地址所需的大小为8个字节。 This is compiler specific.You cannot retrieve the size allocated to a pointer. 这是特定于编译器的。您无法检索分配给指针的大小。

if you getting this doubt,then you should also get a doubt of how does free() will free the memory without knowing the size that has been allocated to the pointer. 如果您对此有疑问,那么您还应该对free()如何释放内存而又不知道已分配给指针的大小有疑问。

我已经在我的Windows 32位计算机上尝试过此操作,我得到的是4字节,我认为ptr是指向int的指针,其显示了正确的信息

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

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