strcat用于动态char指针 [英] strcat for dynamic char pointers
问题描述
我需要用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
是空指针,则不执行任何操作. 否则,如果 该参数与calloc
,malloc
或realloc
函数,或者如果通过调用free
或realloc
释放了空间, 行为是不确定的.
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by thecalloc
,malloc
, orrealloc
function, or if the space has been deallocated by a call tofree
orrealloc
, 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
.
这篇关于strcat用于动态char指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!