读书人

字符串倒序,这个分配在堆上的空间是否

发布时间: 2012-02-09 18:22:27 作者: rapoo

字符串倒序,这个分配在堆上的空间是否释放了?
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>

char *strtemp(char *s);

int main()
{
char source[] = "abcdefg ";
char *str;
str = (char*)malloc(100*sizeof(char));
memset(str, '\0 ',100*sizeof(char));
str = strtemp(source);
printf( "%s ",str);
free(str);
return 0;
}


char *strtemp(char *s)
{
int i;
char *temp;
char *x;
char *y;
int len;
temp = (char*)malloc(100*sizeof(char));//这个是在何时释放的?还是根本就没有释放?
memset(temp, '\0 ',100*sizeof(char));
y = temp;
len = strlen(s);
x = s + len - 1;
for(i = 0;i < len;i++)
{
*y++ = *x--;
}
*(y + len + 1) = '\0 ';
return temp;
}



[解决办法]
1,str = (char*)malloc(100*sizeof(char));
2,str = strtemp(source);//str的值已经改变了,不再指向1处的地址
3,free(str);//释放了在strtemp函数里分配的内存,而在1分配的内存则泄漏了

读书人网 >C++

热点推荐