c - C语言中如何释放指针的内存

标签 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;

}

最佳答案

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

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

关于c - C语言中如何释放指针的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28160158/

相关文章:

c - 在C中设置可执行目录中的文件名

c++ - 将 C/C++ dll 头文件转换为 Delphi 的最佳资源?

无法分配链接描述文件中定义的变量的地址

c - 如何将这个C函数指针转换为delphi函数

c - 使用 gdb 调试 Linux 内核模块

c - 使用带有 c API 的 gstreamer 显示图像

c - 如何 free() 由 malloc() 分配的结构数组?

c - Linux ps命令核心随机

c - 运行功能后菜单获得默认选项

c - 在c中读取一行并转换为字符串