【发布时间】:2018-03-31 21:51:17
【问题描述】:
我有以下 C 函数,这给我带来了很多内存问题,如果我不释放内存它工作正常但是当我调用另一个函数时我得到一个 malloc 内存损坏错误,但我释放它我得到释放无效指针。最后,当我为 fecha 和 fechaVariable 定义新指针时,由于 strtok 的工作很奇怪,我得到了损坏的_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);
}
【问题讨论】:
-
使用新的
strtok_s()函数比旧的strtok()更可取,因为它有一个上下文参数来允许同时进行多个标记化。 -
我更喜欢使用
strncpy()和strncat(),它们都需要最大数量的字符来复制或连接,而不是strcpy()和strcat()函数,以防万一缺少零终止符在从中复制的字符串中。这个想法是通过复制太多来防止缓冲区溢出问题。然后我在最后一个char数组元素中放置一个零终止符,以确保新字符串中始终存在一个零字符串终止符。所以char xArray[100];我会使用strcpy (xArray, aszSource, 100 - 1); xArray[100 - 1] = 0; -
memset(lluvia,'\0',sizeof(lluvia));也有问题,因为lluvia的大小是char *指针的大小,在 32 位机器上为 4 个字节。您需要指定类似1000 * sizeof(char)的内容。 -
你永远不需要乘以
sizeof(char)。
标签: c memory heap-memory free stack-memory