Using C, to print out an array from textFile

前端 未结 2 1598
眼角桃花
眼角桃花 2021-01-25 23:02

I\'m trying to create a code, which reads from textile, and then stores the data into memory, prints out to the screen so the user can read it, but it is still saved into the m

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 23:41

    phrases[i].English = malloc(sizeof(char));
    

    Here the problem lies, you are allocating a single byte and then trying to cram a string into it, which leads to undefined behavior here:

    fscanf(infile,"%s", phrases[i].English);
    

    Generally, you should assume a sensible buffer length and read that, and check whether the new line is contained. If that's not the case, read again into another buffer or enlarge the old one (using realloc). Either that or use a non-standard function like getline that does this already for you under the hood.

    Given that your lines are pretty short sentences, a constant buffer size could suffice (let's call it MAX_LINE), which provides us a little easier way to achieve the same:

    fscanf(infile, "%*[^\n]s", MAX_LINE, buf);
    

    This reads a string of length MAX_LINE into the buffer buf and terminates before the '\n' is encountered.

    When reading strings, you should refrain from using fscanf("%s", buf) and use fgets() or scanf("%*s", MAX_LINE, ...) instead. This ensures that there will be no attempt to write more data than what you specified, avoiding buffer overflows.

    Edit: The nested loop shouldn't be there. You are basically overwriting phrases[i].TextSpeak a total of phraseCounter times for no benefit. And in the process of that you are leaking a lot of memory.

提交回复
热议问题