Eitan Ratner
Eitan Ratner

Reputation: 39

fputs causing error corrupted size vs prev size

I am working on a project in C language and my code keeps crashing of fputs command. This is the code:

void entry_file_creation(int lc, int error_flag_line, char *source_file_name)
{
    int j = 0;
    FILE *entry_ptr = malloc(sizeof(FILE*));
    if (entry_ptr == NULL)
    {
        fprintf(stderr, "\nError, please try again");
        exit(-1);
    }

    while (j < lc)
    {
        if (error_flag_line == 1)
        {
            ++j;
            continue;
        }
        if (label_table[j].extern_entry == 2)
        {
            source_file_name = strtok(source_file_name, ".");
            entry_ptr = fopen(strcat(source_file_name, ".ent"), "w");
            if (entry_ptr == NULL)
            {
                fprintf(stderr, "\nError: something went wrong with creating entry file - '%s'. please try again\n\n", source_file_name);
                exit(-1);
            }
            printf("\nLabel: %s \n", label_table[j].name);
            fputs(label_table[j].name, entry_ptr);
            fputs("\t", entry_ptr);
            fprintf(entry_ptr, "%d\n", label_table[j].address);
        }
        ++j;
    }
    free(entry_ptr);
}

Code crashes on line:

fputs(label_table[j].name, entry_ptr);

The error is corrupted size vs. prev_size: 0x08bfc5b0 please help.

Upvotes: 0

Views: 109

Answers (1)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43558

This allocation doesn't make sense for only a single file handle:

FILE *entry_ptr = malloc(sizeof(FILE*));

Note that it is semantically-incorrect even if you wanted to dynamically allocate a single handle. The proper way to (needlessly) allocate a single handle would be:

FILE **entry_ptr = malloc(sizeof(FILE *)); // *entry_ptr = fopen()

Then you do:

entry_ptr = fopen(strcat(source_file_name, ".ent"), "w");

It effectively loses the pointer to the allocated memory, overwriting it with the returned handle from fopen.

Further, free(entry_ptr) is requested to free a block that it has never allocated.

You probably want FILE *entry_ptr = fopen(...) in every iteration of the loop, closing it with fclose at the end of the iteration.

Upvotes: 3

Related Questions