algorithm - replacing spaces with %20 in c program -


i have written following program replace spaces %20.it works fine. prints garbage values pointer variable ptr though might have been limited 8 characters malloc assigns 8 bytes of memory.

can tell me did go wrong here ? or there in place algorithm ?

void replacespaces(char *inputstr ) {      char *ptr;     int i,length, spacecount=0;     int newlength,j;      (length=0; *(inputstr+length)!='\0';length++ )     {         if (*(inputstr+length)==' ')         {             spacecount++;         }     }     newlength = length + 2*spacecount;     ptr = (char *)malloc(newlength*sizeof(char));      ( = length-1; >=0; i--)     {         if (*(inputstr+i)==' ')         {              *(ptr+newlength-1)='0';             *(ptr+ newlength-2)='2';             *(ptr+newlength-3)='%';             newlength = newlength -3;         }         else         {             *(ptr+newlength-1) = *(inputstr+i);                  newlength = newlength -1;         }     }     ( = 0; *(ptr+i)!='\0'; i++)     {         printf("%c",*(ptr+i));     }   }   

either use calloc() allocate memory ptr or terminate '\0' after allocation.

with code, ptr never gets terminated '\0'.

so either change

ptr = (char *)malloc(newlength*sizeof(char)); 

to

ptr = calloc(newlength*sizeof(char), sizeof(char)); 

or add below line after allocating ptr.

ptr[newlength] = '\0'; 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -