C strcpy() - evil?

前端 未结 17 1393
梦毁少年i
梦毁少年i 2020-12-23 10:50

Some people seem to think that C\'s strcpy() function is bad or evil. While I admit that it\'s usually better to use strncpy() in order to avoid bu

17条回答
  •  执笔经年
    2020-12-23 11:09

    char* dupstr(char* str)
    {
       int full_len; // includes null terminator
       char* ret;
       char* s = str;
    
    #ifdef _DEBUG
       if (! str)
          toss("arg 1 null", __WHENCE__);
    #endif
    
       full_len = strlen(s) + 1;
       if (! (ret = (char*) malloc(full_len)))
          toss("out of memory", __WHENCE__);
       memcpy(ret, s, full_len); // already know len, so strcpy() would be slower
    
       return ret;
    }
    

提交回复
热议问题