如何在C中释放指针的内存

时间:2015-01-26 22:47:24

标签: c

我写了一个程序来连接两个字符串,并确保当没有足够的空间时缓冲区将加倍。

char * strcat_ex(char * * dest, int * n, const char * src){
    int dest_len = 0;
    int src_len = 0;
    if (*dest == NULL)  *n = 0;
    else dest_len = strlen(*dest);
    if (src == NULL)     return *dest;
    else src_len = strlen(src);

    if (dest_len + src_len + 1 > *n) {
        //(1) malloc a new buffer of size 1 + 2 * (strlen(*dest) + strlen(src))
        char * temp;
        temp = (char*) malloc(1 + 2 * (strlen(*dest) + strlen(src)));
        //(2) set '*n' to the size of the new buffer
        *n = 1 + 2 * (strlen(*dest) + strlen(src));
        //(3) copy '*dest' into the beginning of the new buffer
        strcpy(temp, *dest);
        //(4) free the memory '*dest', and then set '*dest' to point to the new buffer
        free(*dest);
        *dest = temp;
    }
    //(5) concatenate 'src' onto the end of '*dest'.
    while (temp) temp++;
    while ((temp++ = src++) =! '\0');
    return *dest;}

并且此代码不起作用。我在“free(* dest)”中得到了分段错误。 请帮忙。非常感谢你!

这是主要功能:

int main(int argc, char * * argv){
    printf("\nTesting strcat_ex(...)\n");
    char * str1;
    str1 = "one";
    char * str2;
    str2 = "two";
    int n;
    n = strlen(str1);
    printf("Before strcat_ex, str1 == %p (%s), str2 == %p (%s)\n", str1, str1, str2, str2);
    strcat_ex(&(str1), &n, str2);
    printf("After swap, str1 == %p (%s), str2 == %p (%s)\n", str1, str1, str2, str2);

return EXIT_SUCCESS;

}

1 个答案:

答案 0 :(得分:0)

问题是str1的初始值是指向文字字符串的指针。该指针无法释放。因此修复是malloc中的main空格,例如

char *str1 = malloc( 100 );  // allocate an initial buffer
int n = 100;                 // the buffer has 100 bytes
strcpy( str1, "one" );       // put some text in the buffer