0

我正在实现一个 strdup 函数作为练习。

char* strdupPtr(const char* str) {
    const size_t sz{strlen(str)+1};
    char *save, *temp;
    save = temp = (char*)malloc(sz);
    while((*temp++ = *str++));  // compiler warning with only 1 set of   parenthesis
    return save;
}

在几次失败后,我发现当返回“保存” (wiki 参考)指针时它可以正常工作,但在返回“临时”时不能正常工作。为什么在处理指针时需要直接返回 save 而不是 temp(下标数组版本不使用 save 也可以工作)?

4

1 回答 1

1

在函数指针temp内递增。

while((*temp++ = *str++));  

因此,如果要返回temp,那么它将不包含已分配内存的起始地址。

例如,这些用例将无效。

char *p = strdup( "Hello World" );

puts( p );

free( p );

考虑到在 C++ 中最好使用 operator new。例如

char * strdupPtr( const char *s ) 
{
    char *p = new char[std::strlen( s ) + 1];

    std::strcpy( p, s );

    return p;
}

或者你甚至可以写

char * strdupPtr( const char *s ) 
{
    char *p = new char[std::strlen( s ) + 1];

    return std::strcpy( p, s );
}
于 2015-07-11T18:44:15.600 回答