views:

106

answers:

2

Hello, I have a javascript file, and I want to translate it in C, I did it but I have a big runtime error. Everything work well until the end of the function when it return an int. If you have some ideas where the bug is. Thanks a lot.

#ifndef max
    #define max( a, b ) ( ((a) > (b)) ? (a) : (b) )
#endif

char *substring(size_t start, size_t stop, const char *src, char *dst, size_t size)
{
   int count = stop - start;
   if ( count >= --size )
   {
      count = size;
   }
   sprintf(dst, "%.*s", count, src + start);
   return dst;
}

int CrackLog(char log[], char pw[])
{
    int tabc=3696619; //7
    char tab[]="                   azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789_$&#@";
    int i,checksum;

        checksum=tabc;
        int nblog=strlen(log);
        int nbpass=6;//6
        int sum=1;
        int n = max(nblog,nbpass);

        for (i=0;i<n;i++)
        {
            char *to;
            to = substring(i, i+1, log, to, sizeof to);
            int index1=strcspn(tab, to)+10;

            to = substring(i, i+1, pw, to, sizeof to);
            int index2=strcspn(tab, to)+10;

            sum=sum+(index1*n*(i+1))*(index2*(i+1)*(i+1));
        }

        if (sum==checksum) {
            return 1;
        }else
                    return 0;
}

Forgive my english I am frensh. Mac Fly

+1  A: 

sprintf requires you allocate the memory yourself.

Try changing char *to; to

char *to = (char*) malloc(sizeof(char)*(stop-start));

where start and stop are the first two arguments to substring

You might have to include stdlib.h if you haven't already

tzenes
Thanks, your answer helped me.
Mac Fly
A: 

It looks like you are looping over the length of the two parameters log and pw. But since n appears as if it might be set to the maximum of those two lengths, then the substring call will be reading past the end of the shorter buffer at some point. In the given code, nbpass is hard coded to 6, so it is unclear exactly what the intent or result will be. Nonetheless, it seems that could be an issue (maybe you want a min result?).

As tzenes correctly points out, you need to make sure that the dst parameter of the substring call has a valid buffer to use. If you use malloc as he suggests, make sure you free it each time (if it is allocated each iteration).

However, the substring function is only extracting one character at a time. If that is the desired result, then the following might be more efficient:

  char to[2];
  to[1] = '\0';  // null terminate
  for (i=0;i<n;i++)
     {
     to[0] = log[i];
     int index1=strcspn(tab, to)+10;

     to[0] = pw[i];
     int index2=strcspn(tab, to)+10;

     sum=sum+(index1*n*(i+1))*(index2*(i+1)*(i+1));
     }
Mark Wilkins
Thanks, the use of malloc and free solved the runtime error.
Mac Fly