0

An array of uint64* (pointer array) prints correct value. When re-print these value in another loop(same copy), the values have changed automatically. In-between there is usage of malloc() function. If i comment out malloc lines g_m and gm_rm then program works fine.

for(i=0;i<num_of_msg_blocks;i++) // loop 1
 printf("%lu -%08x ",i,msg_block[i]);    

g_m= malloc(num_of_msg_blocks+1);
gm_rn= malloc(num_of_msg_blocks+1);

for(i=0;i<num_of_msg_blocks;i++)  //loop 2
 printf("%lu -%08x ",i,msg_block[i]);

Loop 1 output:

0- 00313233 
1- 000a3132 
2- 00330a31 
3- 0032330a 
4- 0061736a 
5- 006b6264 
6- 006b6a61 
7- 0062730a 
8- 00383231 
9- 00343837 
10- 00323334 
11- 00366862 
12- 00776a6b 
13- 000a7364 

Loop 2 output:

0- 00313233 
1- 000a3132 
2- 00330a31 
3- 0032330a 
4- 0061736a 
5- 006b6264 
6- 006b6a61 
7- 0062730a 
8- 00383231 
9- 00343837 
10- 00000031 
11- 00000000 
12- 00776a6b 
13- 000a7364 

From 0-9 both loop output same values, but 10 and onward the values incorrectly changes.

The above variable declaration is as:

uint32_t *msg_block;
msg_block = malloc(num_of_msg_blocks+1);   
uint64_t *g_m;  
uint64_t *gm_rn;

Why printed values depends on malloc, (they are independent) ? How to correct this?

1
  • 3
    Please provide a MVCE. Commented Sep 5, 2019 at 22:48

1 Answer 1

3

You're not allocating enough space for msg_block. You're allocating num_of_msg_blocks+1 bytes, but you need to multiply that by the size of each element.

msg_block = malloc((num_of_msg_blocks+1) * sizeof *msg_block);   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.