Here is my structures:
typedef struct gene{
char* name;
int length;
int* sequence;
} gene;
typedef struct genes{
gene gene;
struct genes* next;
} genes;
constructors:
genes* createGenes(gene newGene){
genes* geneArr = malloc(sizeof(genes));
if (NULL != geneArr){
geneArr->gene = newGene;
geneArr->next = NULL;
}
return geneArr;
}
void deleteGenes(genes* geneArr){
if(NULL != geneArr->next){
deleteGenes(geneArr->next);
}
free(geneArr);
}
genes* addGene(genes* geneList, gene newGene){
genes* toAdd = createGenes(newGene);
if (NULL != toAdd){
geneList->next = toAdd;
}
return geneList;
}
and a function (it creates a sequence with the given length. For 5 -> {2, 2, 2, 2, 2}):
gene twosGene(char* name, int length){
gene newGene;
newGene.name = name;
newGene.length = length;
newGene.sequence = (int*)malloc(sizeof(int) * length);
for(int i = 0; i < length; i++){
newGene.sequence[i] = 2;
}
return newGene;
}
here is my main() function:
int main(){
int count = 1;
genes* geneArr = createGenes(twosGene("gene1", count++));
for (int i = 0; i < 4; ++i) {
geneArr = addGene(geneArr, twosGene("geneLoop", count++));
}
genes* iter;
for (iter = geneArr; NULL != iter; iter = iter->next) {
printf("gene=%d\n", iter->gene.length);
free(iter->gene.sequence);
}
deleteGenes(geneArr);
return 0;
}
I expect this output:
gene=1
gene=2
gene=3
gene=4
gene=5
but instead I'm getting this:
gene=1
gene=5
Also when I use Valgrind, there is some leakage in my program.
==20580== HEAP SUMMARY:
==20580== in use at exit: 132 bytes in 6 blocks
==20580== total heap usage: 11 allocs, 5 frees, 1,244 bytes allocated
I cannot figure it out why. Thanks for your helps.
twosGeneseems like a rather odd function--can you explain the significance of the magic number 2? What sort of structure are you expecting to create (the stdout doesn't print the sequence).addGenesupposed to add to the end of the list or add to the beginning? At the moment it just overwrites thenextpointer of the first element in the list, which isn't what you want.