strcat用于动态char指针 [英] strcat for dynamic char pointers

查看:78
本文介绍了strcat用于动态char指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用C语言编写一个strcat.我尝试了以下操作:

I need to write a strcat in C. I tried below things:

 char * c_strcat( char * str1, const char * str2)
 {

      char * ret = (char *) malloc(1 + strlen(str1)+ strlen(str2) );

     if(ret!=NULL)
     {
         strcpy(ret, str1);
         strcat(ret, str2);

     if(str1 !=NULL) free str1; // If I comment this everything will be fine 
       return ret;
     }

     return NULL;
 }     


 int main()
 {

 char * first = "Testone";
 char *second = "appendedfromhere";

 first = c_strcat(first,second);
 if(second !=NULL) free(second);

// I want to store the result in the same variable 

 }

每当我在c_strcat函数中释放str1内存时,它就会崩溃.如果我不释放空间,那么分配给第一个的内存将被泄漏(如果我理解正确的话).

It crashed whenever I free the str1 memory in the c_strcat function. If I don't free then the memory allocated for the first will be leaked (if I understood properly).

如何将返回值存储到相同的变量中(第一个)?

How to store returned value to same variable (first)?

推荐答案

来自 7.20.3.2 C99标准的免费功能:

free函数导致ptr指向的空间被释放,即 可用于进一步分配.如果ptr是空指针,则不执行任何操作. 否则,如果 该参数与callocmallocrealloc函数,或者如果通过调用freerealloc释放了空间, 行为是不确定的.

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

str1(又名first)不是由三个动态内存分配功能之一分配的,从而导致崩溃. second也是如此.

And str1 (aka first) was not allocated by one of the three dynamic memory allocating functions, causing the crash. Same for second also.

如果不释放空间,则分配给first的内存将泄漏(如果理解正确).

if don't free then the memory allocated for the first will be leaked(if am understood properly).

如果使用malloc()realloc()calloc(),并且以后没有free() d内存,则内存将泄漏.由于字符串文字"Testone"不会动态分配,因此不能释放.

Memory will be leaked if malloc(), realloc() or calloc() is used and the memory is not free()d at a later point. As the string literal "Testone" is not dynamically allocated it must not be freed.

请注意,调用free()之前的指针NULL检查不需要为free(),如上所述,如果指针参数为NULL,则不执行任何操作.

Note that the pointer NULL check prior to invoking free() is unrequired as free(), as described above, does nothing if the pointer argument is NULL.

我是否强制转换malloc的结果?

这篇关于strcat用于动态char指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆