I have a file containing the strings of 3 chromosome, which I want to concatenate into one genome. And then I have to access this concatenated string across multiple threads (I use pthread_t). To to this I have to use pthread_mutex_lock when extracting the data, then I use strcat to concatenate the data which are extracted using the function fai_fetch using const char* and then I am saving the data as a char* (see below).
// genome_size the size of all the chromosomes together
// chr_total the number of chromosomes I wish to concatenate
char* genome = (char*) malloc(sizeof(char) * (genome_size+chr_total));
for (int i = 0; i < chr_total; i++){
pthread_mutex_lock(&data_mutex);
const char *data = fai_fetch(seq_ref,chr_names[i],&chr_sizes[i]);
pthread_mutex_unlock(&data_mutex);
//sprintf(&genome[strlen(genome)],data);
strcat(genome,data);
//sprintf(genome+strlen(genome),data); //All three gives conditional jump or move error
//sprintf(genome,data); // THIS SOLVES VALGRIND ISSUE ONE BUT DOES NOT GIVE A CONCATENATED CHAR*
}
All of this works, but then running valgrind I get
Conditional jump or move depends on uninitialized value(s) referring to the "strcat(genome,data); "
and Uninitialized value was created by a heap allocation referring to "char* genome = (char*) malloc(sizeof(char) * (genome_size+chr_total));"
Based on other StackOverflow answers I tried sprintf(&genome[strlen(genome)],data); and sprintf(genome+strlen(genome),data); instead of strcat. However they too gives the same valgrind message.
The only thing that seems to alleviate this error is using sprintf(genome,data); however then i will not get the full genome but just a single chromosome.
Trying genome += sprintf(genome,data); gives me ./a.out': munmap_chunk(): invalid pointer: and ./a.out': free()
In regards to the "Uninitialized value was created by a heap allocation" error -> then my issue is that I am only able to free that memory after all of the threads are done running. So I am not sure how to initialize the values in the heap allocation when I am using malloc.
Is it possible to solve some of these specific valgrind errors?
strcat(genome,data);
The first error is becausestrcat
requires valid C strings for both parameters. An uninitialised buffer likegenome
contains random garbage and is not a valid C string. Init withgenome[0] = 0;
aftermalloc
. – kaylumgenome+strlen(genome)
That has the same problem. Can't getstrlen
of an uninitalised buffer. – kaylumif (genome != NULL)
before using it. The same should be done fordata
since it is storing the return value of the functionfai_fetch()
. – kiner_shahstrlen()
usesNULL
character to determine end of a string.genome
is just allocated memory frommalloc()
and it can't be sure it's memory hasNULL
characters - there can be garbage data. So, I would suggest you do amemset(genome, '\0', genome_size + chr_total)
after doingmalloc
so as not to have any undefined behavior. – kiner_shah