Charlie Epps
Charlie Epps

Reputation: 3675

Struct initialization problem?

I'm using a struct like this:

define struct _Fragment{
     int a;
     char *seq;
}Fragment;

I want to initialize the struct, and using the malloc() method return a dynamic memory like this

Fragment *frag=malloc(10*sizeof(Fragment));

Then I would using the frag pointer like this:

frag->seq="01001";

Then the problem occurs when I returns a lot of Fragments. the error message said that (using valgrind tool):

Uninitialised value was created by a heap allocation

who can tell me how I can deal with it. thank you!

Upvotes: 3

Views: 4934

Answers (4)

Falaina
Falaina

Reputation: 6685

The issue is malloc does not initialize any of the memory it allocates. Valgrind takes particular care to keep track of any regions of memory that have not been initialized.

You should probably take heed of the error though, the only reason Valgrind (Assuming everything works correctly) should print that error is becuase you attempted to make use of the uninitialized data somewhere, which is probably unintended. The use of unitialized variables is not in the code you have in your question, however.

Upvotes: 2

JaredPar
JaredPar

Reputation: 754725

The problem is that even though you use malloc to allocate memory for a Fragment structure, you haven't initialized any of the values. The memory returned by malloc is not guaranteed to be any specific value so you must explicitly initialize the struct members

Fragment* frag = malloc(10*sizeof(Fragment));
int i = 0;
for ( i = 0; i < 10; i++ ) { 
  frag[i].a = 0;
  frag[i].seq = NULL;
}

If you want guaranteed initialized memory you should use calloc. It has an added cost of zero'ing out the memory but it may not be significant for your app.

Also you should check that malloc actually succeeds :)

Upvotes: 4

Bill Forster
Bill Forster

Reputation: 6297

Your code looks plausible, but in the following line;

Fragment *frag=malloc(10*sizeof(Fragment));

Are you sure you need 10* ?

If you need to allocate 10 Fragments, then you should take responsibility for initializing all 10.

Upvotes: 0

Dave Gamble
Dave Gamble

Reputation: 4174

I'm not sure you have a real problem here, but for proper etiquette, your allocation would be:

Fragment *frag=malloc(10*sizeof(Fragment));
if (frag) memset(frag,0,10*sizeof(Fragment));

Upvotes: 6

Related Questions