使用memset和malloc会冲突吗?
char* buf;
buf = malloc(BUFSIZ);
memset(buf ,0 , BUFSIZ);
我认为memset初始化了大小为BUFSIZ的buf变量,但是malloc也分配了一块大小为BUFSIZE的内存,并将指向块开头的指针返回给变量buf...我不知道是否可以使用memset对于指针,因为它用大小 BUFSIZE 初始化数据,但我们不指向它...... 您能提出任何建议来解决这个问题吗?谢谢
大家,感谢您的回答。所以我明白问题通常来自这样的事实:malloc 可能会失败,然后 buf 将指向 NULL。 也许修复代码缺陷的最佳方法是检查 buf 是否等于 null?
char* buf;
buf = malloc(BUFSIZ);
if(buf!=null)
{
memset(buf ,0 , BUFSIZ);
}
也许修复代码缺陷的最佳方法是检查 buf 是否等于 null?
char* buf;
buf = malloc(BUFSIZ);
if(buf!=null)
{
memset(buf ,0 , BUFSIZ);
}
在实践中 malloc 有可能失败吗?或者这只是一个理论?
char* buf;
buf = malloc(BUFSIZ);
memset(buf ,0 , BUFSIZ);
I think that memset initializes the buf variable with size of BUFSIZ, but malloc also allocates a block of size BUFSIZE of memory and returning a pointer to the beginning of the block to the variable buf... I do not know if memset can be used for pointers because it initialize data with size BUFSIZE but we do not poit to it....
Can you suggests anything to fix this problem, thanks
Hi all and thanks for the answers. So I understood that the problem generally comes from the fact that malloc can fail and then the buf will point to NULL.
And maybe the best way to fix the flaw of the code is to check if buf is equals to null?
char* buf;
buf = malloc(BUFSIZ);
if(buf!=null)
{
memset(buf ,0 , BUFSIZ);
}
Maybe the best way to fix the flaw of the code is to check if buf is equals to null?
char* buf;
buf = malloc(BUFSIZ);
if(buf!=null)
{
memset(buf ,0 , BUFSIZ);
}
Is it possible in practice malloc to fail? Or it is just a theory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看起来很简单。
memset 有点像:
seems pretty straightforward.
memset is a bit like:
memset
相当于:所以,是的,它可以(并且正在)在指针中使用。它将
s
和s
之后的(n-1)
字节设置为c
。memset
is the equivalent of:So, yes, it can be (and is) used in pointers. It sets
s
, and(n-1)
bytes followings
, toc
.前提是 malloc 不会失败并返回 NULL 指针,这样就可以了。
buf
指向分配内存的起始位置,大小为 BUFSIZ 字节。 memset 将 BUFSIZ 字节设置为 0,从 buf 指向的内存开始。Provided that malloc does not fail and return a NULL pointer, this is fine.
buf
points to the start of the allocated memory, which is BUFSIZ bytes big. memset sets BUFSIZ bytes to 0 starting at the memory pointed to bybuf
.该代码没有任何问题,除了分配内存后不检查 NULL 之外。
注意,你也可以使用calloc来分配内存,初始化为0,这样就可以避免memset调用:
There's just no problem with that code, except the fact that you don't check for NULL after allocating memory.
Note that you can also use calloc to allocate memory, initialized with 0, so you can avoid the memset call: