如何在不使用malloc()的情况下创建子字符串

1 c malloc free

我如何实现一个子串函数,如下面的函数返回子字符串,但不在malloc()进程中使用,所以我不必担心使用该free()函数释放代码中其他地方的相关内存.这甚至可能吗?

const char *substring(const char *string, int position, int length)
{
    char *pointer;
    int c;

    pointer = malloc(length+1);

    if (pointer == NULL)
    {
        printf("Unable to allocate memory.\n");
        exit(EXIT_FAILURE);
    }

    for (c = 0 ; c < position -1 ; c++)
        string++;

    for (c = 0 ; c < length ; c++)
    {
        *(pointer+c) = *string;
        string++;
    }

    *(pointer+c) = '\0';

    return substr;
}
Run Code Online (Sandbox Code Playgroud)

更新:2012年12月30日

考虑了所有的答案和评论之后,很明显基本上我正在尝试做的是创建一个动态大小的数组(即子字符串),这在C中是不可能的,因为在某些地方不得不使用某种malloc()功能和后续free()调用子串指针或没有垃圾收集器的帮助.我尝试整合libgc垃圾收集器,正如@elhadi所建议的那样,但到目前为止还没有能够在我的Xcode项目中使用它.所以我选择坚持使用以下代码malloc()和free().

char * subStr(const char* srcString, const int offset, const int len)
{
    char * sub = (char*)malloc(len+1);
    memcpy(sub, srcString + offset, len);
    sub[len] = 0;
    return sub;
}

int main()
{    
    const char * message = "hello universe";
    char * sub = subStr( message, 6, 8 );
    printf( "substring: [%s]", sub );
    free(sub);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*oon 6

我看到两个选择:

如果你可以破坏源字符串(通常是坏事):

{
    string[ position + length] = 0;
    return & string[ position ];
}
Run Code Online (Sandbox Code Playgroud)

注意:(请参阅Cole Johnsons注意:free不再适用于返回的指针!)

如果无法修改源字符串:修改方法签名,以便调用者不必担心:

const char *substring(const char *source, char* destination, int position, int length)
Run Code Online (Sandbox Code Playgroud)

并将修改后的字符串放入目标(并返回).

甚至不要考虑这个:

const char *substring(const char *string, int position, int length)
{
    char *pointer;
    int c;
    static char modifiedString[256];
 ...
    return modifiedString;
}
Run Code Online (Sandbox Code Playgroud)

在函数内部使用静态变量来修改结果...(这不是线程安全的(不可重入!))