What if malloc fails?

前端 未结 10 582
轮回少年
轮回少年 2020-12-09 08:57

If a malloc allocation fails, should we try it again?

In something like this:

char* mystrdup(const char *s)  
{
    char *ab = NULL;

           


        
10条回答
  •  青春惊慌失措
    2020-12-09 09:32

    You are not properly allocating memory malloc function require argument as number of bytes it needs to allocated but you are passing the length of the string so the malloc will reserve memory as per length not per the byte used by your string . You should use sizeof() instead and if still it fails then malloc returns null which represent that there is not enough memory available in the stack to satisfy your requirement. To run your code properly try this:-

    char* mystrdup(const char *s)
    { char *ab = NULL;

    while(ab == NULL) {
        ab=(char*)malloc(sizeof(s));  
    }
    
    strcpy(ab, s);
    return ab;
    

    }

提交回复
热议问题