繁体   English   中英

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

[英]Reading string line by line causes buffer overflow

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM