1

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
MarcoM
  • 13
  • 3

1 Answers1

3

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.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Where do you see pointers hiding behind typedefs? – Robert Harvey Aug 29 '21 at 23:04
  • 1
    @RobertHarvey The CS50 course's provided library provides such a typedef. IMHO the remark is somewhat relevant, but not actionable by the OP – nanofarad Aug 29 '21 at 23:08
  • @RobertHarvey for example `string`. I did not mention that OP has hired it, – 0___________ Aug 30 '21 at 06:58
  • @0___________ Using ```malloc``` as per your answer returns the following error: incompatible pointer to integer conversion initializing 'char' with an expression of type 'void *' [-Werror,-Wint-conversion] char ciphertext = malloc(size); ^ ~~~~~~~~~~~~ – MarcoM Aug 30 '21 at 12:09
  • @MarcoM typo. See amended, BTW you see what is wrong from the messgae. – 0___________ Aug 30 '21 at 12:29