逐行读取字符串会导致缓冲区溢出

问题描述

这是我要运行的代码,我应该逐行读取一系列字符串。

    int i;
    char buf[100];
    int o_size = 16;
    char *output = malloc(o_size * sizeof(char));
    strcpy(output,"");
    
    for(i = 0; i < n; i++){
        fgets(buf,100,stdin);
        strtok(buf,"\n");
        
        char temp[100];
        strcpy(temp,buf);
        strtok(temp," "); // The instruction is stored inside the temp variable
        
        char temp1[100];
        strcpy(temp1,strchr(buf,' ') + 1);
        strcpy(buf,temp1); // The input string is stored inside the buf variable (or the index line in the check case)
        int h_val = poly_hash(buf,x,p,m);
        if(!strcmp(temp,"add")){
             ...
        }
        else if(!strcmp(temp,"del")){
             ...
        }
        else if(!strcmp(temp,"find")){
             ...
        }
        else if(!strcmp(temp,"check")){
             ...
        }
    }

我还写了一个附加到输出字符串的函数,这可能是缓冲区溢出的原因吗?

void to_output(char **output,int *o_size,char *string){
    if(strlen(*output) + strlen(string) >= *o_size){
        *o_size *= 2;
        char *temp = malloc(*o_size * sizeof(char));
        strcpy(temp,*output);
        *output = realloc(*output,*o_size * sizeof(char));
        strcpy(*output,temp);
        free(temp);
    }
    strcat(*output,string);
}

解决方法

更简单的是:

void to_output(char **output,int *o_size,char *string){
    int outlen = strlen(*output) + strlen(string) + 1;
    if (outlen > *o_size) {
        *output = realloc(*output,outlen);
        *o_size = outlen;
    }
    strcat(*output,string);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...