简体   繁体   中英

pointer array changes values, When assigning memery using malloc to other pointers

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?

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);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM