簡體   English   中英

C語言中的內存管理問題

[英]Problems with memory managment in C

我有以下C函數,這使我遇到很多內存問題,如果我不釋放內存,它可以正常工作,但是當我調用另一個函數時,我得到了malloc內存損壞錯誤,但是我釋放了它,我得到了自由無效指針。 最后,由於strtok工作異常,我為fecha和fechaVariable定義了新的指針時,我收到了rupted_size vd prev_size錯誤。 有人能幫我嗎。 這是我的代碼:

void mensual_precipitacion(struct fila *arregloArchivo, char *precipitacion, int estacion){
    float acumulado = 0.00;
    char *fecha;
    char *fechaVariable;

    int i;
    int boolIncorrecto = 1;
    char *mes;
    char *anio;
    char *lluvia;   
    int boolfecha = 1;

    fecha = malloc(1000*sizeof(char));
    fechaVariable = malloc(1000*sizeof(char));
    lluvia = malloc(1000*sizeof(char));



    for(i=0;i<cantDatos;i++){

        if(arregloArchivo[i].numero != estacion){
            continue;
        }
        boolIncorrecto =0; 
        if(boolfecha){
            strcpy(fecha,arregloArchivo[i].fecha);  
            boolfecha = 0;

            fecha = strtok(fecha,"/");

            mes = strtok(NULL,"/");
            anio = strtok(NULL," ");
        }

        strcpy(fechaVariable,arregloArchivo[i].fecha);

        fechaVariable = strtok(fechaVariable,"/");

        fechaVariable = strtok(NULL, "/");

        if(strcmp(mes,fechaVariable) == 0){
            acumulado += arregloArchivo[i].precipitacion;

        }else{

            sprintf(lluvia,"%s/%s:%f[mm]\n",mes,anio,acumulado);
            strcat(precipitacion,lluvia);
            acumulado = 0.00;
            boolfecha = 1;
            memset(lluvia,'\0',sizeof(lluvia));
        }

    }
    if(boolIncorrecto){
        strcpy(lluvia,"Nro de estacion inexistente");
    }else{
        sprintf(lluvia,"%s/%s:%f[mm]\n",mes,anio,acumulado);
    }
    //
        //printf("%s\n",lluvia );
    strcat(precipitacion,lluvia);

    free(fecha);
    free(fechaVariable);    
    free(lluvia);
}

您只能撥打free(ptr)如果值ptr從返回malloc()realloc() 您的代碼稍后將具有:

fecha = strtok(fecha, "/");

因此,當您到達函數末尾時, fecha不再包含執行該操作時最初包含的指針:

fecha = malloc(1000 * sizeof(char));

您應該在循環中使用其他變量,以免丟失原始的fecha指針。

您有以下相同問題:

fechaVariable = strtok(fechaVariable,"/");

因此在這里也請使用其他變量。

實際上,根本沒有充分的理由對這些變量使用動態分配。 只需聲明:

char fecha[1000], fechaVariable[1000], lluvia[1000];

然后將不同的變量與strtok ,因為您不能分配給數組變量。

char *fecha_slash = strtok(fecha, "/");
char *fechaVariable_slash = strtok(fechaVariable, "/");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM