i keep getting valgrind errors in my code and i have no idea how to fix it. :/ the idea is that no matter how much tabs / spaces are between 2 or more words/letters in an input, in the output it should be only one space. for example:
a b c d -> a b c d
code:
char* echo(char* in) {
char buffer[256];
int incounter=0, buffcounter=0;
while(incounter<(strlen(in))) {
if(in[incounter] == ' ' || in[incounter] == '\t') incounter++;
else if(in[incounter] != ' ' && in[incounter] != '\t') {
while(in[incounter] != ' ' && in[incounter] != '\t') {
buffer[buffcounter] = in[incounter]; //53
incounter++;
buffcounter++;
}
buffer[buffcounter] = ' ';
buffcounter++;
}
}
char* out = buffer;
return out;
}
errors:
==20521== Conditional jump or move depends on uninitialised value(s)
==20521== at 0x4010B4: echo (hhush.c:53)
==20521== by 0x4021CA: readCommand (hhush.c:327)
==20521== by 0x402538: main (hhush.c:371)
==20521== Uninitialised value was created by a stack allocation
==20521== at 0x402017: readCommand (hhush.c:301)
==20521==
==20521== Conditional jump or move depends on uninitialised value(s)
==20521== at 0x4010CE: echo (hhush.c:53)
==20521== by 0x4021CA: readCommand (hhush.c:327)
==20521== by 0x402538: main (hhush.c:371)
==20521== Uninitialised value was created by a stack allocation
==20521== at 0x402017: readCommand (hhush.c:301)
thats where i am now, still the same errors
char* echo(char* in,char* buffer){
size_t inlen=strlen(in);
int incounter=0,buffcounter=0;
while(incounter<inlen){
if(in[incounter]==' '||in[incounter]=='\t')incounter++;
else{
while(in[incounter]!=' '&&in[incounter]!='\t'){
buffer[buffcounter]=in[incounter];
incounter++;
buffcounter++;
}
buffer[buffcounter]=' ';
buffcounter++;
}
}
return buffer;
}
i call it with:
char input[256];
fgets(input,sizeof(input),stdin);
...
char buffer[256];
printf("%s\n",echo(input,buffer));
strlen(in)in every loop iteration? It does not change. OTAH, I think this part can simply be removedif(in[incounter] != ' ' && in[incounter] != '\t').