簡體   English   中英

使用memset和malloc是否沖突?

[英]Does using memset and malloc conflict?

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是否有可能失敗? 還是僅僅是理論?

該代碼沒有任何問題,除了您在分配內存后不檢查NULL的事實。

請注意,您還可以使用calloc分配以0初始化的內存,因此可以避免調用memset:

char * buf;

buf = calloc( 1, BUFSIZ );

if( buf == NULL )
{
    /* Error management */
}

只要malloc不失敗並返回NULL指針,就可以了。

buf指向分配的內存的開始,該內存為BUFSIZ字節大。 memset從buf的內存開始,將BUFSIZ字節設置為0。

memset等效於:

void *memset(void *s, int c, size_t n) {
    char *ss = (char *)s;
    while (n--)
        *ss++ = c;
    return s;
}

因此,是的,它可以(並且)用於指針。 它設置s ,和(n-1)個字節以下s ,到c

char* buf; // u declare a pointer, pointing to some random memory area
buf = malloc(BUFSIZ); // you allocate BUFSIZ bytes on the heap and set buf to point to that area.
memset( buf, 0, BUFSIZE ); // the area where buf points to are all set to 0, all BUFSIZE of them.

似乎很簡單。

memset有點像:

for (unsigned char *p = buf; p < buf + BUFSIZE; *p++ = '\0' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM