如何在C中释放指针的内存
我编写了一个程序来压缩两个字符串,并确保在没有足够空间时缓冲区的大小将加倍如何在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;
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
尝试
免费(dest)
insteadhow是如何声明和分配的?您需要显示函数是如何被调用的。我看不出这是如何编译的,因为temp
在步骤(5)中不在范围内。了解如何使用realloc
。如有必要,它将为您节省免费。除此之外,请说明如何调用函数以及如何声明传递给函数的变量。