我正在为字符串编写一些函数,但是我对realloc有问题

问题描述 投票:0回答:1

我正在为字符串编写一些函数,而我在realloc上遇到问题。为什么会出现错误realloc(): invalid pointer: 0x000...

这是我的字符串结构:

typedef struct {
    int length;       /* Length of the String excluding '\0' */
    char * string;    /* pointer to string */
} string;

这是我的字符串创建函数:

string string_create(char content[]) {
    string localString;
    localString.length = 0;
    while (content[localString.length] != '\0') {
        localString.length++;
    }
    localString.string = (char *)calloc((localString.length + 1), sizeof(char));
    localString.string = content;
    return localString;
}

这是我的字符串插入函数:(有问题的函数)

void string_insert(string * btstring, int index, char s[]) {        

    int stringLength = 0;
    while (s[stringLength] != '\0') {
        stringLength++;
    }

    if (stringLength > 0) {
        btstring -> length += stringLength;
        btstring -> string = (char *) realloc((btstring -> string), ((btstring -> length + 1) * sizeof(char)));


        for (int i = 0; i < stringLength; i++) {
            char c = s[i];
            char temp[2] = {0, c};
            int cindex = index + i;
            while (btstring -> string[cindex] != '\0') {
                temp[0] = btstring -> string[cindex];
                btstring -> string[cindex] = temp[1];
                temp[1] = temp[0];
                cindex++;
            }
            temp[0] = btstring -> string[cindex];
            btstring -> string[cindex] = temp[1];
            temp[1] = temp[0];
            cindex++;
            btstring -> string[cindex] = temp[1];
        }

    }

}
c c-preprocessor
1个回答
0
投票

realloc可以在另一个地址处返回请求的内存量(并且可能会失败)。因此,您应该执行以下操作:

    char *tmp;
    btstring->length += stringLength;
    tmp = realloc(btstring->string, btstring->length + 1);
    if (!tmp) return;         // could not allocate the memory
    btstring->string = tmp;   // assign the (new) memory to the string.
© www.soinside.com 2019 - 2024. All rights reserved.