Question

I just ran into the problem. The problem is, that I have a string and I must find the longest consecutive substring in string (so if I have aaaccaaaaaggt it will print "A: 5" without quotation marks)and if there are any, print it where and how long they are. My approach was that I go from the longest possible cnsecutive string length and memset it to acgt (one of them, because it is sorta DNA sequence). the problem is, when I ran the function and it printed me the memsetted string there was something like:

aaaaaaaaaaaaaaaa{Xs⌂▼▐

but honestly, I don't know why.

unsigned int longestSubstrInSequenceO(const char *str)
{

int i = 0;

char *cntrlStr = (char *)malloc((strlen(str)) * sizeof(char));

char *copied  = (char *)malloc((strlen(str)) * sizeof(char));

int size;

strcpy(copied, str);

strLower(copied);

copied[0] = tolower(copied[0]);

printf("%s\n", copied);

for(i; i < strlen(str); i++)
{
    printf("%d\n", (strlen(str) - i + 1));

    memset(cntrlStr, 'a', (strlen(str) - i) * sizeof(char));
    printf("%s\n", cntrlStr);
    if(strstr(copied, cntrlStr) != NULL)
    {
        printf("Longest sequence: %d\n", i);
        break;
    }
    memset(cntrlStr, 'c', (strlen(str) - i + 1) * sizeof(char));
    printf("%s\n", cntrlStr);
    if(strstr(copied, cntrlStr) != NULL)
    {
        printf("Longest sequence: %d\n", i);
        break;
    }
    memset(cntrlStr, 'g', (strlen(str) - i + 1) * sizeof(char));
    printf("%s\n", cntrlStr);
    if(strstr(copied, cntrlStr) != NULL)
    {
        printf("Longest sequence: %d\n", i);
        break;
    }
    memset(cntrlStr, 't', (strlen(str) - i + 1) * sizeof(char));
    printf("%s\n", cntrlStr);
    if(strstr(copied, cntrlStr) != NULL)
    {
        printf("Longest sequence: %d\n", i);
        break;
    }
    memset(cntrlStr, '\0', (strlen(str) - i + 1) * sizeof(char));
    printf("%s\n", cntrlStr);

    free(cntrlStr);
    printf("bbbbbbbbbbb");
    cntrlStr = (char *)malloc((strlen(str) - i + 1) * sizeof(char));


    //memset(cntrlStr, 0, (strlen(str) - i ) * sizeof(char));

}
printf("search end\n");
//strstr();
return 0;
}

So guys please, if you can help me, where I went wrong I'll be very grateful. I don't ask you to write my code, just point me to the root of this problem, or tell me how would you do it (if you could do it better) :) thanks!

Was it helpful?

Solution

You have to allocate space for the null terminator as well

char *cntrlStr = (char *)malloc( (strlen(str) + 1 ) * sizeof(char) );

char *copied  = (char *)malloc( (strlen(str) + 1 ) * sizeof(char) );

The same goes for every other string allocation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top