Suresh
Suresh

Reputation: 141

String issue in c++ : to store MM in int format from ctime()

I have designed a program which will store present month in int format where present month is supplied from ctime() ;
While doing so i am facing problems of not displaying the correct month in the output screen,
My source code for the above program is as follows:

int main()
{
 time_t t;
 char *str,*strM;    // Pointer str to store output from ctime()
 //Pointer strM to store month in Mmm format
 int i,M;    //M to store the int equivalent of strM
 t=time(NULL);
 str=ctime(&t);
 for(i=0;i<3;i++)
  strM[i]=str[4+i];
 M=Convert_M(strM);
 cout<<"MM="<<M;
 getch();
 return 0;
}
int Convert_M(char *strM)
{
 char *s[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
        "Sep","Oct","Nov","Dec"};
 int i;
 for(i=0;i<12;i++)
 {

  if((strcmp(strM,s[i]))==0)
  {
   break;
  }
 }
 return (i+1);
}

In the above code Convert_M() takes the string "Mmm" and returns its equivalent int form,
for eg.:
Today is 25/03/2019 ,
so ctime() output is
Mon Mar 25 15:25:11 2019
therefore, Mmm= Mar
and hence output of Convert_M() should be 3

but, the above code is giving its output as:

MM=13

So, where is the logical error in my code? any help...

Upvotes: 0

Views: 142

Answers (1)

aep
aep

Reputation: 1675

So, where is the logical error in my code? any help...

Rather than logical errors, your code has got an obvious programming bug. In main() function the assignment strM[i] = str[4 + i]; causes undefined behavior and most likely will cause a memory corruption(segmentation fault/crash).

int main ()
{
  time_t t;

  char *str, *strM;
  int i, M;
  t = time (NULL);

  str = ctime (&t);

  for (i = 0; i < 3; i++)
    strM[i] = str[4 + i];

  M = Convert_M (strM);

  cout << "MM=" << M;

  getch ();

  return 0;
}

In your above code, you define strM to be pointer to a char, but the pointer is not initialized and you keep on dereferencing it and assigning values to the memory locations. Uninitialized pointer has an undetermined value, it could point to anywhere yielding an undefined behaviour.

What you could have done instead is to define a char array and pass its first address to your convert_M() function. In this way the pointer which points to the address of the first element of the array is initialized and you would get the expected result from the function. Change your main in the following manner and see the issue getting fixed.

int
main ()
{
  time_t t;

  char *str;
  char strM[4]{0}; // creates an array, 0 initialize it
  int i, M;
  t = time (NULL);

  str = ctime (&t);

  for (i = 0; i < 3; i++)
    strM[i] = str[4 + i];

  M = Convert_M (strM);

  cout << "MM=" << M;

  getch ();

  return 0;
}

Upvotes: 1

Related Questions