N
N
newmersedez2020-11-23 14:07:22
C++ / C#
newmersedez, 2020-11-23 14:07:22

Why does the program crash after clearing a line?

I can't figure out what the error is. The program at this stage processes the lines from the file. Given a file containing instructions of the form:

prior=0 task='Task 1'
prior=0 task='Task 3'
prior=2 task='Task 4'
prior=2 task='Task 5'


I read the prior value into the temp variable, and the string contained in ' ' into the msg_buf string;
I allocate memory for the line correctly, I add '\0' at the end of the line, but after the free(msg_buf) function is executed, the program crashes.... Why is this happening? Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "message.h"

void    message_processing(FILE *file)
{
    int         i, j;
    int         temp = 0, size = 0;
    char        str_buf[BUFSIZ] = {0};
    char        *msg_buf = NULL;
    Message     message;

    while(!feof(file))
    {
        fgets(str_buf, sizeof(str_buf), file);
        strtok(str_buf, "\n");
        i = 6;
        while(isdigit(str_buf[i]))
        {
            temp = temp * 10 + (str_buf[i++] - '0');
        }
        i += 7;
        for(; i < strlen(str_buf) - 1; i++)
        {
            //printf("%c", str_buf[i]);
            msg_buf = (char *)realloc(msg_buf, ++size * sizeof(char) + 1);
            msg_buf[size - 1] = str_buf[i];   
        }
        msg_buf[size] = '\0';
        printf("%s\n", msg_buf);
        free(msg_buf);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2020-11-23
@newmersedez

You clear msg_buf in the same loop. On the second iteration, msg_buf is already cleared and you pass it to realloc and everything falls down.
Try assigning msg_buf = NULL after free.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question