简体   繁体   English

C编程-使用strcat()导致valgrind错误

[英]C Programming - Use of strcat() causing errors in valgrind

I have a function that reads takes a file (from stdin) ,reads the first 3 lines and concatenates them. 我有一个函数读取一个文件(从stdin),读取前3行并将它们连接起来。

char line[LINESIZE];
char *temp_fd = malloc(sizeof(char)*LINESIZE*3);
char *temp_sm = malloc(sizeof(char)*LINESIZE);
char *temp_nm = malloc(sizeof(char)*LINESIZE);

char temp_pc[LINESIZE];

for(i=0;i<3;i++) {
    if (fgets(line, LINESIZE, file) != NULL) {
        strcat(temp_fd,line);

        if (i==0)
            strcpy(temp_sn, line);
        else if(i==1)
            strcpy(temp_nm, line);
        else if(i==2)
            strcpy(temp_pc,line);
    }
}

I get two errors though in valgrind, and i as i understand, strcat is the problem. 我在valgrind中遇到两个错误,据我了解,strcat是问题所在。 How to correctly allocate memory for my pointers? 如何为我的指针正确分配内存? (LINESIZE is 60 btw) (LINESIZE为60 btw)

Thank you! 谢谢!

You aren't doing anything to clear out your buffer space before you use it. 在使用缓冲区之前,您无需做任何事情来清除缓冲区空间。

There are two different ways you could fix it. 您可以使用两种不同的方法来修复它。 Either would work: 任何一种都可以工作:

  • Write a null terminator byte to the head of the buffer before using it (eg strcpy(temp_fd, ""); ) 在使用缓冲区终止符之前,将空终止符字节写入缓冲区的头部(例如strcpy(temp_fd, "");

  • Allocate with calloc instead of malloc calloc而不是malloc分配

Since temp_fd is uninitialized, you should use strcpy instead of strcat the first time you go through the loop. 由于temp_fd未初始化,因此在您第一次执行循环时,应使用strcpy而不是strcat This would copy the string, rather than trying to append it. 这将复制字符串,而不是尝试附加它。

The reason for this is that strcat searches for the location at which to append data before copying the content. 这样做的原因是strcat在复制内容之前会搜索要附加数据的位置。 However, the content of temp_fd is uninitialized at the time when you call strcat , causing the problem. 但是,在调用strcat时, temp_fd的内容未初始化,从而导致了问题。

Alternatively, you could put '\\0' in the initial place of temp_fd right after the allocation, and call strcat in all iterations of the loop: 或者,您可以在分配之后temp_fd'\\0'放在temp_fd的初始位置,然后在循环的所有迭代中调用strcat

char *temp_fd = malloc(sizeof(char)*LINESIZE*3);
temp_fd[0] = '\0';

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

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