Just saw this code:
刚刚看到这段代码:
artist = (char *) malloc(0);
and I was wondering why would one do this?
我想知道为什么要这样做?
17 个解决方案
#1
95
According to the specifications, malloc(0) will return either "a null pointer or a unique pointer that can be successfully passed to free()".
根据规范,malloc(0)将返回“一个空指针或一个可以成功传递到free()的唯一指针”。
This basically lets you allocate nothing, but still pass the "artist" variable to a call to free() without worry. For practical purposes, it's pretty much the same as doing:
这基本上可以让您不分配任何东西,但仍然可以将“artist”变量传递给free(),而不用担心。实际上,它和做的是一样的:
artist = NULL;
#2
39
The C standard says:
C标准说:
If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
如果无法分配空间,则返回空指针。如果所请求的空间大小为零,则行为为实现定义:返回空指针,或行为为非零值,除非返回的指针不用于访问对象。
So, malloc(0)
could return NULL
or a valid pointer that may not be dereferenced. In either case, it's perfectly valid to call free()
on it.
因此,malloc(0)可以返回NULL或一个有效的指针,该指针可能不会被取消。在这两种情况下,调用free()都是完全有效的。
I don't really think malloc(0)
has much use, except in cases when malloc(n)
is called in a loop for example, and n
might be zero.
我并不认为malloc(0)有很大的用处,除非malloc(n)在循环中被调用,n可能为0。
Looking at the code in the link, I believe that the author had two misconceptions:
查看链接中的代码,我认为作者有两个错误的概念:
-
malloc(0)
returns a valid pointer always, and - malloc(0)总是返回一个有效的指针,并且。
-
free(0)
is bad. - 免费(0)是坏的。
So, he made sure that artist
and other variables always had some "valid" value in them. The comment says as much: // these must always point at malloc'd data
.
因此,他确保艺术家和其他变量总是有一些“有效”的价值。该评论说的同样多://这些必须总是指向malloc的数据。
#3
8
malloc(0) behaviour is implementation specific. The library can return NULL or have the regular malloc behaviour, with no memory allocated. Whatever it does, it must be documented somewhere.
malloc(0)行为是特定于实现的。该库可以返回NULL或具有正常的malloc行为,没有分配内存。无论它做什么,它都必须被记录在某个地方。
Usually, it returns a pointer that is valid and unique but should NOT be dereferenced. Also note that it CAN consume memory even though it did not actually allocate anything.
通常,它返回一个有效且唯一的指针,但是不应该取消引用。还要注意,它可以消耗内存,即使它实际上没有分配任何东西。
It is possible to realloc a non null malloc(0) pointer.
可以将非null malloc(0)指针进行realloc。
Having a malloc(0) verbatim is not much use though. It's mostly used when a dynamic allocation is zero byte and you didn't care to validate it.
尽管使用malloc(0)一字不差。它主要用于动态分配为零字节,而您不关心验证它。
#4
4
There's an answer elsewhere on this page that begins "malloc(0) will return a valid memory address and whose range will depend on the type of pointer which is being allocated memory". This statement is incorrect (I don't have enough reputation to comment on that answer directly, so can't put this comment directly under there).
在这个页面的其他地方有一个答案,它开始“malloc(0)将返回一个有效的内存地址,其范围将取决于被分配内存的指针的类型”。这个说法是不正确的(我没有足够的声誉来直接评论这个答案,所以不能直接把这个评论写在下面)。
Doing malloc(0) will not automatically allocate memory of correct size. The malloc function is unaware of what you're casting its result to. The malloc function relies purely on the size number that you give as its argument. You need to do malloc(sizeof(int)) to get enough storage to hold an int, for example, not 0.
使用malloc(0)不会自动分配正确大小的内存。malloc函数不知道您将其结果转换为什么。malloc函数完全依赖于你给出的参数的大小。您需要使用malloc(sizeof(int))来获得足够的存储以容纳int,例如,而不是0。
#5
4
There are a lot of half true answers around here, so here are the hard facts. The man-page for malloc()
says:
这里有很多真实的答案,所以这里有一些确凿的事实。malloc()的手册页说:
If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
如果大小为0,那么malloc()将返回NULL,或一个惟一的指针值,该值稍后可以成功传递给free()。
That means, there is absolutely no guarantee that the result of malloc(0)
is either unique or not NULL. The only guarantee is provided by the definition of free()
, again, here is what the man-page says:
这意味着,绝对不能保证malloc(0)的结果是唯一的或非空的。唯一的保证是由free()的定义提供的,这里是man-page说的:
If ptr is NULL, no operation is performed.
如果ptr为空,则不执行任何操作。
So, whatever malloc(0)
returns, it can safely be passed to free()
. But so can a NULL
pointer.
因此,无论malloc(0)返回什么,它都可以安全地传递给free()。但是空指针也可以。
Consequently, writing artist = malloc(0);
is in no way better than writing artist = NULL;
因此,写作艺术家= malloc(0);没有比写artist = NULL更好的了;
#6
4
I know it's been five years, but my answer may add something and I have a reputation to maintain.
我知道已经5年了,但我的回答可能会增加一些东西,我有维护的声誉。
malloc(0);
can be used in situations where you don't know the exact length of what is coming. If a zero length result is also a possible outcome, there is no use of starting with a minimum allocated size. For example, buffers. If you read a variable number of bytes from somewhere your buffer may grow. You can grow your buffer with realloc()
. But realloc needs a pointer to memory that is already malloc
ed or calloc
ed, and then is when you use malloc(0);
.
malloc(0);在你不知道将要发生什么的情况下可以使用。如果一个零长度的结果也是一个可能的结果,那么从最小的分配大小开始是没有用的。例如,缓冲。如果您从某个地方读取了一个可变的字节数,那么您的缓冲区可能会增长。您可以使用realloc()来增加缓冲区。但是realloc需要一个指向内存的指针,该指针已经被malloced或calloced,然后当您使用malloc(0)时;
char* buffer = malloc(0);
int bytesread = 0;
do
{
//read n bytes from somewhere
buffer = realloc(buffer, bytesread + n); //expand the buffer
//check it is properly allocated
//copy the newly read bytes to the buffer
bytesread += n;
}
while (there_is_still_a_chance_of_reading_more_bytes);
//do something with the complete buffer
free(buffer); //does not really need if(buffer);
Of course. there are other considerations: if you know the number of bytes to be read or that number will be big, then repeatedly reading small numbers of bytes and using memset
is not very efficient.
当然可以。还有其他的考虑:如果您知道要读取的字节数,或者这个数字是大的,那么重复读取少量的字节和使用memset不是很有效。
#7
3
malloc(0)
doesn't make any sense to me, unless the code is relying on behaviour specific to the implementation. If the code is meant to be portable, then it has to account for the fact that a NULL return from malloc(0)
isn't a failure. So why not just assign NULL to artist
anyway, since that's a valid successful result, and is less code, and won't cause your maintenance programmers to take time figuring it out?
malloc(0)对我来说没有任何意义,除非代码依赖于特定于实现的行为。如果代码是可移植的,那么它必须考虑到malloc(0)的NULL返回并不是失败。既然这是一个有效的成功的结果,而且是更少的代码,而且不会让维护程序员花时间去解决它,为什么不给它分配一个NULL呢?
malloc(SOME_CONSTANT_THAT_MIGHT_BE_ZERO)
or malloc(some_variable_which_might_be_zero)
perhaps could have their uses, although again you have to take extra care not to treat a NULL return as a failure if the value is 0, but a 0 size is supposed to be OK.
malloc(SOME_CONSTANT_THAT_MIGHT_BE_ZERO)或malloc(some_variable__might_be_0)可能会有它们的用途,不过,如果值为0,那么您需要特别小心不要将NULL返回视为失败,但是0大小应该是可以的。
#8
2
Admittedly, I have never seen this before, this is the first time I've seen this syntax, one could say, a classic case of function overkill. In conjunction to Reed's answer, I would like to point out that there is a similar thing, that appears like an overloaded function realloc
:
不可否认,我以前从未见过这种情况,这是我第一次看到这种语法,有人会说,这是一个典型的功能过度的例子。在里德的回答中,我想指出的是,有一个类似的东西,看起来像一个重载的函数realloc:
- foo is non-NULL and size is zero,
realloc(foo, size);
. When you pass in a non-NULL pointer and size of zero to realloc, realloc behaves as if you’ve called free(…) - foo非null,大小为0,realloc(foo, size);当您传递一个非空指针并将其大小为0到realloc时,realloc的行为就像您调用了free(…)
- foo is NULL and size is non-zero and greater than 1,
realloc(foo, size);
. When you pass in a NULL pointer and size is non-zero, realloc behaves as if you’ve called malloc(…) - foo为NULL,大小为非0,大于1,realloc(foo, size);当您传递一个空指针和大小是非0时,realloc的行为就像您调用malloc(…)
Hope this helps, Best regards, Tom.
希望这对你有帮助,最好的问候,汤姆。
#9
2
To actually answer the question made: there is no reason to do that
回答这个问题:没有理由这样做。
#10
1
Why you shouldn't do this...
为什么你不应该这么做…
Since malloc's return value is implementation dependent, you may get a NULL pointer or some other address back. This can end up creating heap-buffer overflows if error handling code doesn't check both size and returned value, leading to stability issues (crashes) or even worse security issues.
由于malloc的返回值是依赖于实现的,所以您可以返回一个空指针或其他地址。如果错误处理代码没有检查大小和返回值,导致稳定性问题(崩溃)或者更糟糕的安全问题,那么这可能会导致堆缓冲区溢出。
Consider this example, where further accessing memory via returned address will corrupt heap iff size is zero and implementation returns a non NULL value back.
考虑这个例子,通过返回的地址进一步访问内存将导致堆iff大小为零,实现返回一个非空值。
size_t size;
/* Initialize size, possibly by user-controlled input */
int *list = (int *)malloc(size);
if (list == NULL) {
/* Handle allocation error */
}
else {
/* Continue processing list */
}
See this Secure Coding page from CERT Coding Standards where I took the example above for further reading.
从CERT编码标准看这个安全的编码页,我在上面举了一个例子来进一步阅读。
#11
0
Not sure, according to some random malloc source code I found, an input of 0 results in a return value of NULL. So it's a crazy way of setting the artist pointer to NULL.
不确定,根据我找到的一些随机的malloc源代码,输入的0会导致返回值为NULL。这是将艺术家指针设为空的疯狂方法。
http://www.raspberryginger.com/jbailey/minix/html/lib_2ansi_2malloc_8c-source.html
http://www.raspberryginger.com/jbailey/minix/html/lib_2ansi_2malloc_8c-source.html
#12
0
malloc(0) will return NULL or a valid pointer which can be rightly passed to free. And though it seems like the memory that it points to is useless or it can't be written to or read from, that is not always true. :)
malloc(0)将返回NULL或一个有效的指针,该指针可以正确地传递给free。虽然这似乎是它指向的记忆是无用的,或者它不能被写入或读取,但这并不总是正确的。:)
int *i = malloc(0);
*i = 100;
printf("%d", *i);
We expect a segmentation fault here, but surprisingly, this prints 100! It is because malloc actually asks for a huge chunk of memory when we call malloc for the first time. Every call to malloc after that, uses memory from that big chunk. Only after that huge chunk is over, new memory is asked for.
我们期望在这里有一个分段错误,但是令人惊讶的是,这将打印100!这是因为malloc在我们第一次调用malloc时请求了大量的内存。每一次对malloc的调用,都使用了那个大数据块的内存。只有在那个巨大的数据块结束之后,才会要求新的内存。
Use of malloc(0): if you are in a situation where you want subsequent malloc calls to be faster, calling malloc(0) should do it for you (except for edge cases).
使用malloc(0):如果您想要后续的malloc调用更快,那么调用malloc(0)应该为您(除了边界情况)做它。
#13
0
According to Reed Copsey answer and the man page of malloc , I wrote some examples to test. And I found out malloc(0) will always give it a unique value. See my example :
根据Reed Copsey的回答和malloc的手册,我写了一些例子来测试。我发现malloc(0)总是给它一个独特的值。看看我的例子:
char *ptr;
if( (ptr = (char *) malloc(0)) == NULL )
puts("Got a null pointer");
else
puts("Got a valid pointer");
The output will be "Got a valid pointer", which means ptr
is not null.
输出将“得到一个有效指针”,这意味着ptr不为空。
#14
0
In Windows:
在Windows中:
-
void *p = malloc(0);
will allocate a zero-length buffer on the local heap. The pointer returned is a valid heap pointer. - void * p = malloc(0);将在本地堆上分配一个零长度的缓冲区。返回的指针是有效的堆指针。
-
malloc
ultimately callsHeapAlloc
using the default C runtime heap which then callsRtlAllocateHeap
, etc. - malloc最终使用默认的C运行时堆调用HeapAlloc,然后调用RtlAllocateHeap,等等。
-
free(p);
usesHeapFree
to free the 0-length buffer on the heap. Not freeing it would result in a memory leak. - *(p);使用HeapFree在堆上释放0长度的缓冲区。不释放它会导致内存泄漏。
#15
0
Here is the analysis after running with valgrind memory check tool.
这是经过valgrind记忆检查工具运行后的分析。
==16740== Command: ./malloc0
==16740==
p1 = 0x5204040
==16740==
==16740== HEAP SUMMARY:
==16740== in use at exit: 0 bytes in 0 blocks
==16740== total heap usage: 2 allocs, 2 frees, 1,024 bytes allocated
==16740==
==16740== All heap blocks were freed -- no leaks are possible
and here's my sample code:
这是我的样本代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
//int i;
char *p1;
p1 = (char *)malloc(0);
printf("p1 = %p\n", p1);
free(p1);
return 0;
}
By default 1024 bytes is allocated. If I increase the size of malloc, the allocated bytes will increase by 1025 and so on.
默认情况下,分配1024字节。如果增加malloc的大小,那么分配的字节将增加1025,以此类推。
#16
-3
malloc(0)
will return a valid memory address and whose range will depend on the type of pointer which is being allocated memory. Also you can assign values to the memory area but this should be in range with the type of pointer being used. You can also free the allocated memory. I will explain this with an example:
malloc(0)将返回一个有效的内存地址,其范围将取决于被分配内存的指针的类型。您还可以将值分配给内存区域,但这应该在使用的指针类型的范围内。您还可以释放已分配的内存。我将用一个例子来解释这个问题:
int *p=NULL;
p=(int *)malloc(0);
free(p);
The above code will work fine in a gcc
compiler on Linux machine. If you have a 32 bit compiler then you can provide values in the integer range, i.e. -2147483648 to 2147483647. Same applies for characters also. Please note that if type of pointer declared is changed then range of values will change regardless of malloc
typecast, i.e.
以上代码将在Linux机器上的gcc编译器中运行良好。如果您有一个32位的编译器,那么您可以提供整数范围内的值,即-2147483648到2147483647。同样适用于字符。请注意,如果已声明的指针类型被更改,那么无论malloc类型是什么,值的范围都会改变。
unsigned char *p=NULL;
p =(char *)malloc(0);
free(p);
p
will take a value from 0 to 255 of char since it is declared an unsigned int.
将从0到255的值取一个值,因为它被声明为unsigned int。
#17
-3
Just to correct a false impression here:
为了纠正错误的印象:
artist = (char *) malloc(0);
will never ever return NULL
; it's not the same as artist = NULL;
. Write a simple program and compare artist
with NULL
. if (artist == NULL)
is false and if (artist)
is true.
艺术家= (char *) malloc(0);永远不会返回NULL;它与artist = NULL不同;编写一个简单的程序并将艺术家与NULL进行比较。如果(artist == NULL)是假的,如果(artist)是真的。
#1
95
According to the specifications, malloc(0) will return either "a null pointer or a unique pointer that can be successfully passed to free()".
根据规范,malloc(0)将返回“一个空指针或一个可以成功传递到free()的唯一指针”。
This basically lets you allocate nothing, but still pass the "artist" variable to a call to free() without worry. For practical purposes, it's pretty much the same as doing:
这基本上可以让您不分配任何东西,但仍然可以将“artist”变量传递给free(),而不用担心。实际上,它和做的是一样的:
artist = NULL;
#2
39
The C standard says:
C标准说:
If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
如果无法分配空间,则返回空指针。如果所请求的空间大小为零,则行为为实现定义:返回空指针,或行为为非零值,除非返回的指针不用于访问对象。
So, malloc(0)
could return NULL
or a valid pointer that may not be dereferenced. In either case, it's perfectly valid to call free()
on it.
因此,malloc(0)可以返回NULL或一个有效的指针,该指针可能不会被取消。在这两种情况下,调用free()都是完全有效的。
I don't really think malloc(0)
has much use, except in cases when malloc(n)
is called in a loop for example, and n
might be zero.
我并不认为malloc(0)有很大的用处,除非malloc(n)在循环中被调用,n可能为0。
Looking at the code in the link, I believe that the author had two misconceptions:
查看链接中的代码,我认为作者有两个错误的概念:
-
malloc(0)
returns a valid pointer always, and - malloc(0)总是返回一个有效的指针,并且。
-
free(0)
is bad. - 免费(0)是坏的。
So, he made sure that artist
and other variables always had some "valid" value in them. The comment says as much: // these must always point at malloc'd data
.
因此,他确保艺术家和其他变量总是有一些“有效”的价值。该评论说的同样多://这些必须总是指向malloc的数据。
#3
8
malloc(0) behaviour is implementation specific. The library can return NULL or have the regular malloc behaviour, with no memory allocated. Whatever it does, it must be documented somewhere.
malloc(0)行为是特定于实现的。该库可以返回NULL或具有正常的malloc行为,没有分配内存。无论它做什么,它都必须被记录在某个地方。
Usually, it returns a pointer that is valid and unique but should NOT be dereferenced. Also note that it CAN consume memory even though it did not actually allocate anything.
通常,它返回一个有效且唯一的指针,但是不应该取消引用。还要注意,它可以消耗内存,即使它实际上没有分配任何东西。
It is possible to realloc a non null malloc(0) pointer.
可以将非null malloc(0)指针进行realloc。
Having a malloc(0) verbatim is not much use though. It's mostly used when a dynamic allocation is zero byte and you didn't care to validate it.
尽管使用malloc(0)一字不差。它主要用于动态分配为零字节,而您不关心验证它。
#4
4
There's an answer elsewhere on this page that begins "malloc(0) will return a valid memory address and whose range will depend on the type of pointer which is being allocated memory". This statement is incorrect (I don't have enough reputation to comment on that answer directly, so can't put this comment directly under there).
在这个页面的其他地方有一个答案,它开始“malloc(0)将返回一个有效的内存地址,其范围将取决于被分配内存的指针的类型”。这个说法是不正确的(我没有足够的声誉来直接评论这个答案,所以不能直接把这个评论写在下面)。
Doing malloc(0) will not automatically allocate memory of correct size. The malloc function is unaware of what you're casting its result to. The malloc function relies purely on the size number that you give as its argument. You need to do malloc(sizeof(int)) to get enough storage to hold an int, for example, not 0.
使用malloc(0)不会自动分配正确大小的内存。malloc函数不知道您将其结果转换为什么。malloc函数完全依赖于你给出的参数的大小。您需要使用malloc(sizeof(int))来获得足够的存储以容纳int,例如,而不是0。
#5
4
There are a lot of half true answers around here, so here are the hard facts. The man-page for malloc()
says:
这里有很多真实的答案,所以这里有一些确凿的事实。malloc()的手册页说:
If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
如果大小为0,那么malloc()将返回NULL,或一个惟一的指针值,该值稍后可以成功传递给free()。
That means, there is absolutely no guarantee that the result of malloc(0)
is either unique or not NULL. The only guarantee is provided by the definition of free()
, again, here is what the man-page says:
这意味着,绝对不能保证malloc(0)的结果是唯一的或非空的。唯一的保证是由free()的定义提供的,这里是man-page说的:
If ptr is NULL, no operation is performed.
如果ptr为空,则不执行任何操作。
So, whatever malloc(0)
returns, it can safely be passed to free()
. But so can a NULL
pointer.
因此,无论malloc(0)返回什么,它都可以安全地传递给free()。但是空指针也可以。
Consequently, writing artist = malloc(0);
is in no way better than writing artist = NULL;
因此,写作艺术家= malloc(0);没有比写artist = NULL更好的了;
#6
4
I know it's been five years, but my answer may add something and I have a reputation to maintain.
我知道已经5年了,但我的回答可能会增加一些东西,我有维护的声誉。
malloc(0);
can be used in situations where you don't know the exact length of what is coming. If a zero length result is also a possible outcome, there is no use of starting with a minimum allocated size. For example, buffers. If you read a variable number of bytes from somewhere your buffer may grow. You can grow your buffer with realloc()
. But realloc needs a pointer to memory that is already malloc
ed or calloc
ed, and then is when you use malloc(0);
.
malloc(0);在你不知道将要发生什么的情况下可以使用。如果一个零长度的结果也是一个可能的结果,那么从最小的分配大小开始是没有用的。例如,缓冲。如果您从某个地方读取了一个可变的字节数,那么您的缓冲区可能会增长。您可以使用realloc()来增加缓冲区。但是realloc需要一个指向内存的指针,该指针已经被malloced或calloced,然后当您使用malloc(0)时;
char* buffer = malloc(0);
int bytesread = 0;
do
{
//read n bytes from somewhere
buffer = realloc(buffer, bytesread + n); //expand the buffer
//check it is properly allocated
//copy the newly read bytes to the buffer
bytesread += n;
}
while (there_is_still_a_chance_of_reading_more_bytes);
//do something with the complete buffer
free(buffer); //does not really need if(buffer);
Of course. there are other considerations: if you know the number of bytes to be read or that number will be big, then repeatedly reading small numbers of bytes and using memset
is not very efficient.
当然可以。还有其他的考虑:如果您知道要读取的字节数,或者这个数字是大的,那么重复读取少量的字节和使用memset不是很有效。
#7
3
malloc(0)
doesn't make any sense to me, unless the code is relying on behaviour specific to the implementation. If the code is meant to be portable, then it has to account for the fact that a NULL return from malloc(0)
isn't a failure. So why not just assign NULL to artist
anyway, since that's a valid successful result, and is less code, and won't cause your maintenance programmers to take time figuring it out?
malloc(0)对我来说没有任何意义,除非代码依赖于特定于实现的行为。如果代码是可移植的,那么它必须考虑到malloc(0)的NULL返回并不是失败。既然这是一个有效的成功的结果,而且是更少的代码,而且不会让维护程序员花时间去解决它,为什么不给它分配一个NULL呢?
malloc(SOME_CONSTANT_THAT_MIGHT_BE_ZERO)
or malloc(some_variable_which_might_be_zero)
perhaps could have their uses, although again you have to take extra care not to treat a NULL return as a failure if the value is 0, but a 0 size is supposed to be OK.
malloc(SOME_CONSTANT_THAT_MIGHT_BE_ZERO)或malloc(some_variable__might_be_0)可能会有它们的用途,不过,如果值为0,那么您需要特别小心不要将NULL返回视为失败,但是0大小应该是可以的。
#8
2
Admittedly, I have never seen this before, this is the first time I've seen this syntax, one could say, a classic case of function overkill. In conjunction to Reed's answer, I would like to point out that there is a similar thing, that appears like an overloaded function realloc
:
不可否认,我以前从未见过这种情况,这是我第一次看到这种语法,有人会说,这是一个典型的功能过度的例子。在里德的回答中,我想指出的是,有一个类似的东西,看起来像一个重载的函数realloc:
- foo is non-NULL and size is zero,
realloc(foo, size);
. When you pass in a non-NULL pointer and size of zero to realloc, realloc behaves as if you’ve called free(…) - foo非null,大小为0,realloc(foo, size);当您传递一个非空指针并将其大小为0到realloc时,realloc的行为就像您调用了free(…)
- foo is NULL and size is non-zero and greater than 1,
realloc(foo, size);
. When you pass in a NULL pointer and size is non-zero, realloc behaves as if you’ve called malloc(…) - foo为NULL,大小为非0,大于1,realloc(foo, size);当您传递一个空指针和大小是非0时,realloc的行为就像您调用malloc(…)
Hope this helps, Best regards, Tom.
希望这对你有帮助,最好的问候,汤姆。
#9
2
To actually answer the question made: there is no reason to do that
回答这个问题:没有理由这样做。
#10
1
Why you shouldn't do this...
为什么你不应该这么做…
Since malloc's return value is implementation dependent, you may get a NULL pointer or some other address back. This can end up creating heap-buffer overflows if error handling code doesn't check both size and returned value, leading to stability issues (crashes) or even worse security issues.
由于malloc的返回值是依赖于实现的,所以您可以返回一个空指针或其他地址。如果错误处理代码没有检查大小和返回值,导致稳定性问题(崩溃)或者更糟糕的安全问题,那么这可能会导致堆缓冲区溢出。
Consider this example, where further accessing memory via returned address will corrupt heap iff size is zero and implementation returns a non NULL value back.
考虑这个例子,通过返回的地址进一步访问内存将导致堆iff大小为零,实现返回一个非空值。
size_t size;
/* Initialize size, possibly by user-controlled input */
int *list = (int *)malloc(size);
if (list == NULL) {
/* Handle allocation error */
}
else {
/* Continue processing list */
}
See this Secure Coding page from CERT Coding Standards where I took the example above for further reading.
从CERT编码标准看这个安全的编码页,我在上面举了一个例子来进一步阅读。
#11
0
Not sure, according to some random malloc source code I found, an input of 0 results in a return value of NULL. So it's a crazy way of setting the artist pointer to NULL.
不确定,根据我找到的一些随机的malloc源代码,输入的0会导致返回值为NULL。这是将艺术家指针设为空的疯狂方法。
http://www.raspberryginger.com/jbailey/minix/html/lib_2ansi_2malloc_8c-source.html
http://www.raspberryginger.com/jbailey/minix/html/lib_2ansi_2malloc_8c-source.html
#12
0
malloc(0) will return NULL or a valid pointer which can be rightly passed to free. And though it seems like the memory that it points to is useless or it can't be written to or read from, that is not always true. :)
malloc(0)将返回NULL或一个有效的指针,该指针可以正确地传递给free。虽然这似乎是它指向的记忆是无用的,或者它不能被写入或读取,但这并不总是正确的。:)
int *i = malloc(0);
*i = 100;
printf("%d", *i);
We expect a segmentation fault here, but surprisingly, this prints 100! It is because malloc actually asks for a huge chunk of memory when we call malloc for the first time. Every call to malloc after that, uses memory from that big chunk. Only after that huge chunk is over, new memory is asked for.
我们期望在这里有一个分段错误,但是令人惊讶的是,这将打印100!这是因为malloc在我们第一次调用malloc时请求了大量的内存。每一次对malloc的调用,都使用了那个大数据块的内存。只有在那个巨大的数据块结束之后,才会要求新的内存。
Use of malloc(0): if you are in a situation where you want subsequent malloc calls to be faster, calling malloc(0) should do it for you (except for edge cases).
使用malloc(0):如果您想要后续的malloc调用更快,那么调用malloc(0)应该为您(除了边界情况)做它。
#13
0
According to Reed Copsey answer and the man page of malloc , I wrote some examples to test. And I found out malloc(0) will always give it a unique value. See my example :
根据Reed Copsey的回答和malloc的手册,我写了一些例子来测试。我发现malloc(0)总是给它一个独特的值。看看我的例子:
char *ptr;
if( (ptr = (char *) malloc(0)) == NULL )
puts("Got a null pointer");
else
puts("Got a valid pointer");
The output will be "Got a valid pointer", which means ptr
is not null.
输出将“得到一个有效指针”,这意味着ptr不为空。
#14
0
In Windows:
在Windows中:
-
void *p = malloc(0);
will allocate a zero-length buffer on the local heap. The pointer returned is a valid heap pointer. - void * p = malloc(0);将在本地堆上分配一个零长度的缓冲区。返回的指针是有效的堆指针。
-
malloc
ultimately callsHeapAlloc
using the default C runtime heap which then callsRtlAllocateHeap
, etc. - malloc最终使用默认的C运行时堆调用HeapAlloc,然后调用RtlAllocateHeap,等等。
-
free(p);
usesHeapFree
to free the 0-length buffer on the heap. Not freeing it would result in a memory leak. - *(p);使用HeapFree在堆上释放0长度的缓冲区。不释放它会导致内存泄漏。
#15
0
Here is the analysis after running with valgrind memory check tool.
这是经过valgrind记忆检查工具运行后的分析。
==16740== Command: ./malloc0
==16740==
p1 = 0x5204040
==16740==
==16740== HEAP SUMMARY:
==16740== in use at exit: 0 bytes in 0 blocks
==16740== total heap usage: 2 allocs, 2 frees, 1,024 bytes allocated
==16740==
==16740== All heap blocks were freed -- no leaks are possible
and here's my sample code:
这是我的样本代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
//int i;
char *p1;
p1 = (char *)malloc(0);
printf("p1 = %p\n", p1);
free(p1);
return 0;
}
By default 1024 bytes is allocated. If I increase the size of malloc, the allocated bytes will increase by 1025 and so on.
默认情况下,分配1024字节。如果增加malloc的大小,那么分配的字节将增加1025,以此类推。
#16
-3
malloc(0)
will return a valid memory address and whose range will depend on the type of pointer which is being allocated memory. Also you can assign values to the memory area but this should be in range with the type of pointer being used. You can also free the allocated memory. I will explain this with an example:
malloc(0)将返回一个有效的内存地址,其范围将取决于被分配内存的指针的类型。您还可以将值分配给内存区域,但这应该在使用的指针类型的范围内。您还可以释放已分配的内存。我将用一个例子来解释这个问题:
int *p=NULL;
p=(int *)malloc(0);
free(p);
The above code will work fine in a gcc
compiler on Linux machine. If you have a 32 bit compiler then you can provide values in the integer range, i.e. -2147483648 to 2147483647. Same applies for characters also. Please note that if type of pointer declared is changed then range of values will change regardless of malloc
typecast, i.e.
以上代码将在Linux机器上的gcc编译器中运行良好。如果您有一个32位的编译器,那么您可以提供整数范围内的值,即-2147483648到2147483647。同样适用于字符。请注意,如果已声明的指针类型被更改,那么无论malloc类型是什么,值的范围都会改变。
unsigned char *p=NULL;
p =(char *)malloc(0);
free(p);
p
will take a value from 0 to 255 of char since it is declared an unsigned int.
将从0到255的值取一个值,因为它被声明为unsigned int。
#17
-3
Just to correct a false impression here:
为了纠正错误的印象:
artist = (char *) malloc(0);
will never ever return NULL
; it's not the same as artist = NULL;
. Write a simple program and compare artist
with NULL
. if (artist == NULL)
is false and if (artist)
is true.
艺术家= (char *) malloc(0);永远不会返回NULL;它与artist = NULL不同;编写一个简单的程序并将艺术家与NULL进行比较。如果(artist == NULL)是假的,如果(artist)是真的。