-1

I've got an issue i can't handle so i've thought maybe you can help me. Basically i have a function that receives a char* as a paramater and does some stuff to it(i've checked those steps/functions and they work just fine).If the char* given in the function is ""(i guess NULL), i receive seg fault with assert. Here is the code:

char *computeRNA(char *s)
{
    if (s != NULL && s!= "")
    {
        Lista* l = to_list(s);
        int i;
        l = l->next;
        for(i = 0; i<= lungime(l); ++i)
        {
            if(l->info == 'T')
                l->info = 'U';
            l = l->next;
        }
        char *rna = to_pointer(l);
        return rna;

    }
        return NULL;
}

And here is the assert:

 char *s;
   s = computeRNA("");
    ASSERT(!strcmp(s, ""), "computeRNA-01");
    free(s);

This is a school homework so i can not change assert's code , only the function.Thanks in advance !

2 Answers2

0

You cannot pass a NULL pointer to strcmp() as argument. Before the ASSERT statement, just check for non-NULL value of s. Something like

if (s) {
  ASSERT(!strcmp(s, ""), "computeRNA-01");
 }

should do the job.


EDIT:

In case changing the function using the assertion is also not possible, you can modify the computeRNA() function to return an empty string, instead of NULL, like

char * empty_string = calloc(1,1);
return empty_string;

which can later be passed to free() in the caller.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

This ASSERT that you weren't supposed to be changing, tests that if an empty string is given to computeRNA it should also return an empty string:

s = computeRNA("");
ASSERT(!strcmp(s, ""), "computeRNA-01");

Your code returns null pointer. Also comparing strings needs to be done using strcmp, s == "" would only compare pointer values that wouldn't be of use here.

Thus I'd start the function with

// null pointer was given
if (!s) {
    return calloc(1, 1);
}

// an empty string was given (the first character pointed to b s is the string terminator.)
// to compare explicitly, you need to do `strcmp(s, "")` == 0. `s == ""` is wrong.
if (!*s) {
    return "";
}