Reputation: 23
I am Running a code for valgrind
int fun(char* str) {
char* prt1;
char* ptr2;
char sstr[20];
strcpy(sstr, "\0");
ptr1 = str;
ptr2 = sstr;
while (((isspace(*ptr1)) || (iscntrl(*ptr1))) && (*ptr1 != '\0'))
ptr1++;
while (*ptr1 != '\0')
*ptr2++ = *ptr1++;
while (((isspace(*(ptr2 - 1))) || (iscntrl(*(ptr2 - 1)))) && (ptr2 > str))
ptr2++;
*ptr2 = '\0' strcpy(str, (S8*)sstr);
return (strlen(ptr1));
}
getting this error Use of uninitialised value of size 8 for line
while (((isspace (*(ptr2-1))) || (iscntrl (*(ptr2-1)))) &&
(ptr2 > str))
If i put the NULLP
check before assigning to the pointers this is error is gone
if (ptr1 != NULLP && ptr2 != NULLP) {
ptr1 = str;
ptr2 = sstr;
}
Is it with Valgrind code error or the check should be included ?
Thanks for the help .
Upvotes: 1
Views: 2092
Reputation: 9904
No the check for NULLP is completely wrong and in fact invokes undefined behaviour as the pointers are not initialized at that time.
The real problem is that when you first enter the loop
while (((isspace (*(ptr2-1))) || (iscntrl (*(ptr2-1)))) && (ptr2 > str))
you check the last char copied, and if that's a white space or control character you increment ptr2
and now you check the first char you have never initialized.
(left aside the fact that the condition also is wrong for the case that you haven't copied any character. Then isspace(*(ptr2-1))
would invoke UB as well)
If you want to trim sstr
(is it so?), your loop should be
while ( ptr2 > sstr && ( isspace (ptr2[-1]) || iscntrl (ptr2[-1]) ) )
ptr2--;
Note the differences:
ptr2
with sstr
instead of str
and do it first, so that isspace()
and iscntrl()
are not executed if ptr2 == sstr
ptr2--
instead of ptr2++
Upvotes: 3
Reputation: 145
I think if you change this line:
while (((isspace (*(ptr2-1))) || (iscntrl (*(ptr2-1)))) && (ptr2 > str))
to this:
while ((ptr2 > str) && ((isspace (*(ptr2-1))) || (iscntrl (*(ptr2-1)))))
You won't get the error. It looks like you could be reading before the
beginning of str
, since your check ptr2 > str
will occur after the
dereference. Moving this check to the beginning of the conditional allows
it to short circuit.
Upvotes: 1