0

I am trying to implement a function to generate a random string consisting of only a-z characters both upper and lower case.. What is wrong with the code I wrote and how can I fix it? I am constantly getting "Segmentation fault" no matter what I try to do or change..

string random(int length)
{

    string set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";        
    string word = "";

    for (int i = 0; i < length; i++)
    {
        word[i] = set[rand() % 52];
    }

    return word;
}

1 Answer 1

1

This string word = ""; sets word to a "string literal", and as such it is stored in read-only memory, ie it's immutable; therefore you cannot do this word[i] = set[rand() % 52];. That's what is giving the seg fault.

4
  • When a string is first created, the length is fixed. Setting it as "" or NULL fixes it as one char, the end of string marker. If you want to create a string without defining the contents, you need to declare something like string word[30];. This will create a char array of 30 characters without initializing the contents. I your case, you probably want to do string word[length+1];
    – Cliff B
    Dec 16, 2016 at 23:05
  • You could allocate it as a "regular" char*. Something like char* word = calloc(length + 1,1);. I cannot think of a way using a cs50 string, because it "black-boxes" allocation. Dec 16, 2016 at 23:10
  • Or what @CliffB said :) Dec 16, 2016 at 23:11
  • Trying everything just introduced me to another error.. what ended up working for me at the end was "string word = malloc(length);" Not 100% sure what malloc does but it works!
    – Ethan
    Dec 17, 2016 at 1:20

You must log in to answer this question.

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