Code error used for dynamic assignment!..

Asked 2 years ago, Updated 2 years ago, 29 views

#include<stdio.h>
#include<stdlib.h>
void main(void)
{
    char *mes;
    char *mes2;
    char *mes3;
    int i, j,temp=1;

    FILE *fp = fopen("Readme.txt", "rb");
    FILE *fp2 = fopen("readm.txt", "wb");
    long dw;


    if (fp)
    {
        dw = ftell(fp);
        fseek(fp, 0, SEEK_END);
        dw = ftell(fp);
        mes = (char*)malloc(dw);

        fseek(fp, 0, SEEK_SET);
        fread(mes, 1, dw, fp);
        for(i=0;i<dw;i++)
            if (mes[i] == 'i' && mes[i + 1] == 's')
            {
                mes2 = (char*)malloc(dw + temp);
                mes2 = mes;
                mes2[i] = 'a';
                mes2[i + 1] = 'r';
                memmove(mes2 + i + 3, mes2 + i + 2, strlen(mes2) - i + 3);
                mes2[i + 2] = 'e';
                temp++;
                free(mes2);



        }
        mes = (char*)malloc(dw + temp);
        mes = mes2;
        printf("mes:%s\n", mes);

    }

    free(mes2);
    free(mes);
    fclose(fp);
    fclose(fp2);
}

I'm going to change the letter is to are in the txt file using dynamic assignment. But I keep getting errors I want to know how to fix it!

c

2022-09-22 19:53

1 Answers

Are you talking about the error message "pointer being free was not allotted"? This error means, "There is nothing assigned to the pointer you want to free!" Looking at the code, mes2 and mes are free twice.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char *mes = NULL;
    char *mes2 = NULL;
    char *mes3 = NULL;
    int i, j,temp=1;

    FILE *fp = fopen("File.txt", "rb");
    long dw;

    if (fp)
    {
        dw = ftell(fp);
        fseek(fp, 0, SEEK_END);
        dw = ftell(fp);
        mes = (char*)malloc(dw);

        fseek(fp, 0, SEEK_SET);
        fread(mes, 1, dw, fp);
        for(i=0;i<dw;i++)
            if (mes[i] == 'i' && mes[i + 1] == 's')
            {
                mes2 = (char*)malloc(dw + temp);
                mes2 = mes;
                mes2[i] = 'a';
                mes2[i + 1] = 'r';
                memmove(mes2 + i + 3, mes2 + i + 2, strlen(mes2) - i + 3);
                mes2[i + 2] = 'e';
                temp++;
                free(mes2); // where mesh2 is free.


            }
        mes = (char*)malloc(dw + temp);
        mes = mes2;
        printf("mes:%s\n", mes);

    }

    Free(mes2); // There will be an error if I try to free up the free mesh2 from above, right?
    Free(mes); // mesh has the same value as mesh2, but an error occurs because mesh2 is already free above.
    fclose(fp);
}

If you clear the last free(mes2); free(mes); there will be no error. Also, there are unnecessary variables in the code and memory leaks!


2022-09-22 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.