I have a string which I need to concat some data onto the end. My problem is that each time the loop goes round I get previous loop data on the end of my string. e.g data
1st loop iteration 1234@3 2nd loop iteration 3462@3@124 3rd loop iteration 3676@3@124@67 and so on..
what i need to do is receive the string and some data to the end, set the string for each loop iteration.
if(rank == 0)
{
char *recv_str = malloc(PRECISION);
int retVal = -10;
int len;
long exp;
char *str_exp = malloc(sizeof(char) * 8);
char *deli = "@";
for(i=1; i<= size - 1 ; i++)
{
MPI_Recv(&exp,1,MPI_LONG,i,1,MPI_COMM_WORLD,&status);
MPI_Recv(&len,1,MPI_INT,i,1,MPI_COMM_WORLD,&status);
MPI_Recv(recv_str,len, MPI_CHAR, i, 1,MPI_COMM_WORLD, &status);
sprintf(str_exp, "%lu", exp);
sprintf(recv_str + strlen(recv_str), deli);
sprintf(recv_str + strlen(recv_str),str_exp);
retVal = mpf_set_str(pi_ret, recv_str, 10);
//printf("string = %s \n", recv_str);
//printf("\nvalid? %d length %d\n", retVal, len);
//printf("str_exp = %s \n", str_exp);
mpf_add(pi, pi, pi_ret);
//printf("\nsize of %lu \n", strlen(recv_str));
}
Do it this way:
char * recv_str = malloc(PRECISION * sizeof(*recv_str)); /* Make sure PRECISION is large enough!!! */
...
char str_exp[32] = ""; /* Make it's large enough to hold the decimal representaion of a long. */
char * deli = "@";
if (NULL == recv_str)
{
perror("malloc() failed for recv_str");
assert(1);
}
for(i=1; i<= size - 1 ; i++)
{
strcpy(recv_str, ""); /* Reset the "string" to "empty" before each iteration! */
...
sprintf(str_exp, "%ld", exp);
assert(sizeof(recv_str) <= (strlen(recv_str) + strlen(deli)));
strcat(recv_str, deli);
assert(sizeof(recv_str) <= (strlen(recv_str) + strlen(str_exp)));
strcat(recv_str, str_exp);
...
}
free(recv_str);
Update:
As it showed that initialsing recv_str
to 0
-length by doing
strcpy(recv_str, "");
did not solve the problem, as it most probably only sets the "string"'s 1st byte to NUL
/'\0'
, the more radical approach needed to be taken to clear out the whole "string" with 0
s by doing:
memset(recv_str, 0, PRECISION * sizeof(*recv_str));