Hey guys,

I'm loading from a dictionary with a variable called "buffer". I'm trying to copy "buffer" in to another array word for word. For some reason, when I try using strncpy(), it yields a segfault. Here is my code (assuming "LETTERS" is 29:

bool load(string filename)
    // open dictionary
    FILE* file = fopen(filename, "r");
    if (file == NULL)
        return false;

    // load words from dictionary
    char buffer[LETTERS + 2];

    int size = 0;

    while (fgets(buffer, LETTERS + 2, file))
        // overwrite \n with \0
        buffer[strlen(buffer) - 1] = '\0';

        strncpy(arrayList[size], buffer, LETTERS + 2);

    return true;

So I've tried printing the value of "buffer", and it prints just fine. I have no idea why this isn't working.

What is "arrayList", and why are you copying Letters + 2? IMO, you should be using strcpy(), instead of strncpy(), since the words will have different lengths.

Segmentation error occurs when you are trying to access an array outside its range.

@ Adak

and why are you copying Letters + 2?

OP is not copying LETTERS + 2. He is specifying the maximum number of characters to be copied from source.

Each string in 'arrayList' has to have enough space to store LETTERS+2 characters plus 1 for the null character if you're using strncpy().

So you have to declare 'arrayList' as char arrayList[100][LETTERS+2+1]; or something similiar.

Or perhaps your 'arrayList' doesn't have enough space, so you could be going past the maximum size with size=102 strncpy(arrayList[102], buffer, LETTERS + 2);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.