问题描述
看着刚刚问过的这个问题:指向静态变量的指针的不便那样做会被认为是不好的做法吗?
Looking at this question that has just been asked: Inconveniences of pointers to static variables would doing something like this be considered bad practice, then?
char* strpart(char* string, int start, int count)
{
char* strtemp;
int i = 0; int j = 0;
int strL = strlen(string);
if ( count == 0 )
{
count = strL;
}
strtemp = (char*) calloc((count + 1), sizeof(char));
for ( i = start; i < (start+count); i++ )
{
strtemp[j] = string[i];
j++;
}
return strtemp;
}
很抱歉,它写得很快,但是基本原理是-当在函数内部不使用静态缓冲区时,在函数内部分配内存是不好的做法吗?我想是因为它不会被释放,对吗?以为我应该问.
Sorry it's written quickly, but the basic principle is - when NOT using a static buffer inside a function is it bad practice to assign memory inside a function? I assume so because it wouldn't be freed, would it? Thought I ought to ask though.
推荐答案
这不错,但很容易造成内存泄漏(调用者必须记住要释放内存).
It's not bad pratice but it can easily create memory leaks (the callers have to remember to free the memory).
我想做的一件事是使用命名约定来指示可以分配哪些函数.例如,我要将该函数命名为:
One thing I like to do is use a naming convention to indicate what functions can allocate. For example, I'd name that function:
char* strpart_alloc(char* string, int start, int count)
这篇关于Calloc内部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!