简体   繁体   English

malloc分配的内存大小

[英]size of memory allocated by malloc

I am assigning a new memory chunk to a pointer, but apparently the size of the chunk is not the one which I pass as a parameter to malloc 我正在为一个指针分配一个新的内存块,但是显然,该块的大小不是我作为参数传递给malloc的大小

char *q="tre";
printf("q in main %zu\n", sizeof(q));
q = (char*)malloc(6);
printf("q in main %zu\n", sizeof(q));

Outputs 输出

8
8

The pointer however does point to a new memory chunk. 但是指针确实指向一个新的内存块。 How is this possible? 这怎么可能?

sizeof returns size of pointer, in your case it is (char*) , it will not give the memory allocated by the malloc . sizeof返回指针的大小,在您的情况下为(char*) ,它将不提供malloc分配的malloc Keep the memory size in separate variable for later use. 将内存大小保留在单独的变量中,以备后用。

char *q;
printf("%zu\n", sizeof(q));

sizeof(q) refers to the size of the pointer, not the amount of memory it points to. sizeof(q)是指指针的大小,而不是它指向的内存量。

What you are obtaining is the size of the variable q as a pointer type. 您获得的是变量q的大小作为指针类型。 In general all pointers will have the same size in your program. 通常,所有指针在程序中的大小都相同。

Since 8 bytes are 64 bits, it seems you are doing 64-bit applications. 由于8个字节是64位,因此您似乎正在执行64位应用程序。 :) :)

sizeof(q) returns the size of the pointer q which will on a 64 bit machine be 8 bytes, not the size of the memory block allocated at that pointer. sizeof(q)返回指针q的大小,该指针在64位计算机上为8字节,而不是在该指针处分配的内存块的大小。 sizeof is a compile time not a runtime operation. sizeof是编译时间,而不是运行时操作。

I'm not clear what you want to do here, but if you want to allocate enough memory for a string at location s , then you want to malloc(strlen(s)+1) (+1 for the terminating NULL ). 我不清楚您要在这里做什么,但是如果您想为位置s的字符串分配足够的内存,则需要malloc(strlen(s)+1) (对于终止NULL +1)。

Perhaps you want to get the size of malloc() ed block. 也许您想获取malloc() ed块的大小。 There is not a portable way to do this to my knowledge, but malloc_usable_size nearly does it on glibc . 据我所知,没有一种可移植的方法来执行此操作,但是malloc_usable_sizeglibc上几乎可以执行此操作。 From the man page: 从手册页:

malloc_usable_size() returns the number of bytes available in the dynamically allocated buffer ptr, which may be greater than the requested size (but is guaranteed to be at least as large, if the request was successful). malloc_usable_size()返回动态分配的缓冲区ptr中可用的字节数,该字节数可能大于请求的大小(但如果请求成功,则保证至少与请求的大小相同)。 Typically, you should store the requested allocation size rather than use this function. 通常,您应该存储请求的分配大小,而不要使用此功能。

Note the last sentence. 注意最后一句话。

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

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