动态给char* 分配了空间如何去释放

swallowfyx swallowfyx 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
void leftcut(char *dst,char *src, short n)
{

int len = strlen(src);

if(n>len) n = len;

int i = 0 ;
while(n--)
{
dst[i] = src[i];
i++;
}
dst[i]='\0';

}


前几天在做一个程序的时候用到了要截取char*类型字符串左边部分的功能。在网上看到了这样的一个算法。
用了确实有效。但是用来存放dst的空间是动态分配的。

比如:

int num = 10 ;
char * dst = (char *)malloc(sizeof(char)*num);
leftcut(dst,src,5);
cout<<dst<<endl;
free(dst);

当用完了dst之后对其进行释放。但是总会出错。原因尚不清楚。
以前是对它直接赋值就没法释放,后来搞清楚了。用strcpy去赋值就没问题了。
这次作为参数传递给函数调用之后又没办法释放了。
这个要怎么改呢。

此函数原型:(存在同样的问题)
char * left(char *dst,char *src, int n)
{
char *p = src;
char *q = dst;
int len = strlen(src);
if(n>len) n = len;
/*p += (len-n);*/ /*从右边第n个字符开始*/
while(n--) *(q++) = *(p++);
*(q++)='\0'; /*有必要吗?很有必要*/
return dst;
}



...全文
评论 18
收藏 已收藏
分享
返回顶部
swallowfyx
C语言 70,039 成员 243,237 内容