I am very new to C and working through a project as a way to help motivate me to learn. I was having a hard time getting the output from an sh popen. After much searching and hours of trial and i stumbled across a very old post where they used
strcpy(str + size - 1,buf);
This was the first and only example of this i could find and it is working. It looks like it overwrites the termination character at the end of str with what's in buf. Is that safe? I still havent fully gotten the grasp of how it stores all of this data and changing that number on the end to anything higher than a +2 causes segmentation faults or invalid next size. The full code is below
int dns_probe(char * hostname)
{
char * digLoop[4] = {"ns ","a ","cname ","mx "};
int i;
char outage[1];
char *str = NULL;
char *temp = NULL;
unsigned int size = 1;
unsigned int strlength;
for ( i = 0; i < 4; i++)
{
char *digcmd = concatCMD(digLoop[i],hostname);
FILE * dig = popen(digcmd,"r");
char bufer[256];
while(fgets(buf,sizeof(buf),dig) != 0){
strlength = strlen(buf);
temp = realloc(str, size + strlength);
str = temp;
strcpy(str + size - 1,buf);
size += strlength;
}
pclose(dig);
free(digcmd);
}
printf("%s",str);
}
Really just wanna make sure I am not setting myself up with problems down the road.