1

Every time I try to allocate memory for array of strings, my program fails with an error message "error reading characters of strings". What am I doing wrong? Is there any problem with my memory allocation?

char** file2array(char *filename)
{
    FILE *fp = fopen(filename, "r");

    int i;
    int max_line_len = 20;
    int num_lines = 6;
    char** lines = (char **) malloc(sizeof(char*) * (num_lines + 1));

    fseek(fp, 0, SEEK_END);
    int chars_num = ftell(fp);
    rewind(fp);

    for (i = 1; i < (num_lines + 1); i++) {
        lines[i] = (char *) malloc(max_line_len + 1);
        fgets(lines[i], chars_num, fp);
    }

    fclose(fp);
    return lines;
}
1
  • The second parameter to fgets is wrong. Commented Nov 20, 2015 at 22:07

1 Answer 1

1

You appear to have not presented the code that actually emits the error message, so it's hard to be certain what it's complaining about. You certainly do, however, have a problem with your loop indexing:

    for (i = 1; i < (num_lines + 1); i++) {
        lines[i] = /* ... */

Variable i runs from 1 through num_lines, never taking the value 0, thus the first pointer in your dynamic array of pointers (at index 0) is never initialized. That's a plausible explanation for why some later code might have a problem reading the characters.

Additionally, you use fgets() wrongly. You tell it that your buffers are chars_num bytes long, but they are actually max_line_len + 1 bytes long. This presents the possibility of a buffer overrun.

Indeed, I'm uncertain what the point of chars_num is supposed to be. You initialize it to the length of the file (provided that that length fits in an int), but I'm not seeing how that's useful.

Furthermore, your function may return unexpected results if the file being read has lines longer than you account for (20 bytes, including line terminator) or a different number of lines than you expect (6).

I don't see any inherent problem with your memory allocation, but it wouldn't be StackOverflow if I didn't give you a severe tongue-lashing for casting the return value of malloc(). Consider yourself flogged.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.