Search code examples
ccomputer-sciencecs50edx

free(): invalid pointer Aborted (core dumped) cs50


I'm having problem with substitution cipher that I can't figure out my code functions correctly but it prints extra exclamation mark at the end of my ciphertext here is my important part of the code

int keylen = strlen(argv[1]);
string key = argv[1];
printf("ciphertext: ");
for (int i = 0; i < keylen; i++)
{
    //if it is a lower character we remove the value of a
    //to make it the letters start form 0
    if (islower(plaintext[i]))
    {
        int x = plaintext[i] - 'a';
        printf("%c", tolower(key[x]));
    }
    // the same goes here for uppercase
    else if (isupper(plaintext[i]))
    {
        int y = plaintext[i] - 'A';
        printf("%c", toupper(key[y]));
    }
    else
    {
        //if the text is not an alphabet letter print it as it is
       printf("%c", plaintext[i]);
    }
}

This is the output ~/pset2/substitution/ $ ./subs JTREKYAVOGDXPSNCUIZLFBMWHQ

plaintext: hello

ciphertext: vkxxn!

Then I tried adding this in the loop after the if statement that checks for uppercase like so:

else if (isupper(plaintext[i]))
{
    int y = plaintext[i] - 'A';
    printf("%c", toupper(key[y]));
}
    // breaks at \0 to prevent printing garbage values
else if (plaintext[i] = '\0')
{
    break;
}

and I get this weird error ~/pset2/substitution/ $ ./subs JTREKYAVOGDXPSNCUIZLFBMWHQ

plaintext: hello

ciphertext: vkxxn

free(): invalid pointer

Aborted (core dumped)

I apologize for this lengthy question and thank you all for your time.


Solution

  • I found the code that makes the error

    else if (plaintext[i] = '\0')
    {
        break;
    }
    

    Here I'm assigning the value to '\0' instead of checking the value by double equal signs ==
    that what gives that error

    free(): invalid pointer
    Aborted (core dumped)

    Thanks for your time again