0

I've gotten Vigenere to work via printing each encrypted character as the program runs through the plaintext. I'd now like to create an empty string, and add the new encrypted values into that string, to print as a whole later.

I've used the two following initiators:

string cipher = "a";

and

char cipher[] = "";

before running a loop to run through each character, example:

if (isupper(c))
 {
    char nc = ((c-65+keychar)%26)+65;
    k++;
    cipher[i] = nc; //add new value into empty string. 
 }

For each method, the code compiles but my error is "Segmentation fault." Is there a better / standard way to do this? Thank you!

1

string cipher = "a"; creates a char* of name cipher and lets it point to a string constant of value "a" (that's two bytes, 97 and 0). That area is read-only. Not the way to go.

char cipher[] = ""; creates an array of char with a length matching the string constant used for initialisation. In this case, it's the empty string containing one byte of 0. So this time, your array is writable, but too short.

You'd have to use like char cipher[strlen(plain) + 1] = ""; instead (assuming input string to be named plain). The initialisation is not necessary if you do something like cipher[strlen(plain)] = '\0'; later. You could save the length in a variable to avoid calling strlen multiple times.

Another way would be to malloc/free memory on the heap (you'll get to that in pset4).

Alternatively, you could change your input string (as you don't need it later). It's not read-only.

Or just print the characters while translating, without saving them to a string. You could use like printf("%c", nc); or putchar(nc);.

3
  • Cool - so I had done 'print while translating' working, and now created a new string as a copy of the original plaintext to edit. I'll play around with char cipher[strlen(plain) + 1] then! Thanks! – Jake Jun 4 '18 at 16:32
  • Quick follow, this worked: char cipher[strlen(plaintext)]; – Jake Jun 4 '18 at 16:44
  • 1
    No, it didn't work. You just got lucky that the next byte in memory following the string was 0. It's absolutely necessary to have room for the end of string marker, \0 or a number of other processes won't work reliably, starting with printf. So, while [strlen(plaintext)] is unreliable and unpredictable, [strlen(plaintext)+1] works, as long as you insert the \0 in the last slot. – Cliff B Jun 4 '18 at 20:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .