微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决逐行读取字符串会导致缓冲区溢出

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

    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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。