Reputation: 21
I have a function that reads takes a file (from stdin) ,reads the first 3 lines and concatenates them.
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. How to correctly allocate memory for my pointers? (LINESIZE is 60 btw)
Thank you!
Upvotes: 2
Views: 894
Reputation: 726559
Since temp_fd
is uninitialized, you should use strcpy
instead of strcat
the first time you go through the loop. 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. However, the content of temp_fd
is uninitialized at the time when you call strcat
, causing the problem.
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:
char *temp_fd = malloc(sizeof(char)*LINESIZE*3);
temp_fd[0] = '\0';
Upvotes: 3
Reputation: 16290
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 (e.g. strcpy(temp_fd, "");
)
Allocate with calloc
instead of malloc
Upvotes: 4