0
votes

I have the following function:

string encipher(string plaintext, string key)
{
    int size = strlen(plaintext);
    char ciphertext[size];
    // For each alphabetic characters determine what letter it map to
    for(int i = 0; i < size; i++ )
    {
           for(int j = 0; k[j] != plaintext[i]; j++)
           {
               ciphertext[i] = key[j];
           }
    }
    return ciphertext;
}

Unfortunately when I compile it returns me the following error:

error: address of stack memory associated with local variable 'ciphertext' returned [-Werror,-Wreturn-stack-address] return ciphertext; ^~~~~~~~~~

I tried static and malloc but I am not sure to understand how the stack allocation works.

1
Does this answer your question? Returning string from C function - kaylum
is this a CS50 question? - M.M
Where does string come from? - Robert Harvey
@M.M yes, it's pset2/substitution - MarcoM

1 Answers

2
votes

Arrays in C are passed by reference, and you do not return the array only pointer to it.

char ciphertext[size];

is a local automatic variable which ceases to exist when the function returns - thus any reference to it is invalid.

What to do? You need to dynamically allocate the string:

string encipher(string plaintext, string key)
{
    int size = strlen(plaintext);
    char *ciphertext = malloc(size);
    // check for allocation errors
    // remember to free this memory when not needed
    // For each alphabetic characters determine what letter it map to
    for(int i = 0; i < size; i++ )
    {
           for(int j = 0; k[j] != plaintext[i]; j++)
           {
               ciphertext[i] = key[j];
           }
    }
    return ciphertext;
}

or buffer should be allocated by the caller

string encipher(char *ciphertext, string plaintext, string key)
{
    int size = strlen(plaintext);
    // For each alphabetic charaters determine what letter it map to
    for(int i = 0; i < size; i++ )
    {
           for(int j = 0; k[j] != plaintext[i]; j++)
           {
               ciphertext[i] = key[j];
           }
    }
    return ciphertext;
}

BTW hiding pointers behind typedefs is a very bad practice.