LeetCode替换空格

请问这样为什么会报错呢?好像是内存的问题。


char* replaceSpace(char* s){
    int n=strlen(s);
    int count=0;
    for(int i=0;i<n;i++){
        if(s[i]==' '){
            count++;
        }
    }
    char *str=(char*)malloc(sizeof(char)*(n+2*count+1));
    for(int i=0,j=0;i<n;i++,j++){
        if(s[i]==' '){
            str[j]='%';
            str[j+1]='2';
            str[j+2]='0';
            j+=2;
        }
        else{
            str[j]=s[i];
        }
    }
    return str;
}

str字符串最后加上\0应该就行了。