Strange problem with strcspn in Visual Studio 2012

advertisements

I have this strange issue with strcspn() in Visual Studio 2012.

When I compile the following code as a 32 bit Win32 console application I get the expected result of 6.

#include <string>
#include <iostream>
#include <cstring>

int main( int argc, char **argv )
{
  char delimiter_ = ',';
  std::string css_ = "ESCAPE,,0,0";

  printf( "%s\n", css_.c_str(  ) );
  printf( "%d\n", strcspn( css_.c_str(  ), &delimiter_ ) );

  size_t lengthOfField = strcspn( css_.c_str(  ), &delimiter_ );
  printf( "%d\n", lengthOfField );

  std::cin.get(  );

  return 0;
}

However, if I compile this same code for x64, I get the unexpected result of 4. Is there something I should no or is this a bug in VS2012? This issue exists when using either cstring or string.h for the strcspn() method.

In a separate project, at one point the problem exists but instead of showing a result of 4 in x64, it shows for Win32 but shows 6 for x64. In a different file in this same project the issue is the same as above. It would appear to be some sort of UB but clearly the code given can reproduce this issue and as far as I know I haven't introduced any UB here.

EDIT: After some further testing, using cout instead of printf the values returned have also been 0 and 1.


strcspn need pointers to null terminated strings as both params, you need to fix you code as following.

char delimiter_[] = ",";
printf( "%d\n", strcspn( css_.c_str(  ), delimiter_ ) );