0
if( (*ptr != ',') || strlen(ptr+1) < sizeof(struct A) * num1)
{
    printf("\n Condition satisfied.");
}

This is the code in question. I have a string of the format str = "-1,ABCDEFGH", and a struct A of size 15 bytes.

I'm performing this operation beforehand:

number = strtoul(str, &ptr, 10);

After this operation, ptr points to the ',' and number = -1

Looking at the IF condition, the first statement evaluates to be false (because *ptr = ',') and the second statement executes to be TRUE even though it should be false ( strlen(ptr+1) is positive, and (sizeof(struct A) * number) is negative, simply because num1 is a negative value ).

Why is this statement evaluating to be true and entering the IF block? I'm getting the output 'Condition satisfied', whereas I shouldn't be. Thanks in advance.

  • If you know that the second statement is evaluating incorrectly, why show us the first one? Remove the first one, verify that what remains still produces the error, and give us a [minimal complete example](http://stackoverflow.com/help/mcve). – Beta Sep 12 '15 at 02:16
  • Both `strlen` and `sizeof` use an unsigned type, and you haven't shown us the type of `num1`. So either `num1` is `unsigned` in which case `-1` is a very large positive number, OR you're ignoring the compiler warning about "signed versus unsigned comparison". – user3386109 Sep 12 '15 at 02:16
  • I'm going to already guess you're doing something very wrong with `sizeof(struct A)`. The only time you should be relying on `sizeof()` when used on a struct is doing `memcpy()` operations. My gut instinct tells me you might be trying to do a string length check erroneously, and aren't aware of struct padding. http://stackoverflow.com/questions/4306186/structure-padding-and-structure-packing – Cloud Sep 12 '15 at 02:31

2 Answers2

4

(sizeof(struct A) * number) is negative, simply because num1 is a negative value

Not quite. sizeof(struct A) has type size_t (unsigned type).

Assuming that

  • num is of type int,
  • precision of signed type, corresponding to size_t is the same as or bigger than precision of int,

sizeof(struct A) * num is an unsigned value (and hence non negative), even if num is negative.

See Arithmetic operators:

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Please note, as @user3386109 commented, that strlen uses an unsigned type too. So there could be the same problem with < as with *.

AlexD
  • 32,156
  • 3
  • 71
  • 65
-2

sizeof(struct A) is undefined and also it is multiplied by a number so it provides a