Strange unsigned char * problems in C

So, I have a method that returns unsigned char *

unsigned char* someMethod(num) unsigned short num; { //do some stuff with num and change values of a unsigned char * a = (unsigned char*) malloc(4); printf("a0 is %x\n",a[0]); printf("a1 is %x\n",a[1]); printf("a2 is %x\n",a[2]); printf("a3 is %x\n",a[3]); return a; } 

When I called someMethod (128):

 unsigned char* s = someMethod(128); printf("s0 is %x\n",s[0]); printf("s1 is %x\n",s[1]); printf("s2 is %x\n",s[2]); printf("s3 is %x\n",s[3]); 

He will print

 a0 is 30 a1 is 1 a2 is 31 a3 is 30 s0 is 30 s1 is 14 s2 is ffffff9d s3 is 0 

This makes no sense to me as I assign s = someMethod (128). Should a and s have the same values?!? Any help is appreciated. Thanks!

+4
source share
2 answers

Regarding the comment by @ gl3829, I would go with

 unsigned char *a = malloc(4 * sizeof(*a)) 

so that the size is "automatically" correct.

More importantly, I think the problem is that in someMethod you print the values ​​in a selected array before assigning anything. This causes undefined behavior and allows you to get any results. Try to save something before printing them.

To print unsigned char in hexadecimal, the correct format specifier is %hhx . Using the wrong qualifier can also cause undefined behavior.

+1
source

When you print to %x , the printf() function reads int . int on 32-bit computers is 4 bytes long. Therefore, the 2nd, 3rd, and 4th printf() are read both inside and inside the malloc() . You cannot expect areas outside of what you malloc'd always remain unchanged.

There is a solution, put it down. Malloc is a few bytes larger, maybe sizeof(int) larger than what you currently want.


Solution 2: first enter those s[i] in int before passing it to printf()

+1
source

All Articles