"C" malloc problem! Help!

Status
Not open for further replies.

superluminal

I am MalcomR
Valued Senior Member
Ok, I have this problem.

Here's part of the header for your information:
Code:
typedef unsigned char       UB1;
typedef unsigned short int UB2;
typedef unsigned int         UB4;

UB1 *ld_data_base;
UB4 *ld_data_ptr;
UB1 *data_item;

I malloc the two vars as shown. 'ld_data_base' is a block that will contain some variable length strings or other data. 'ld_data_ptr' is a list of pointers hat will point to the beginning of each variable length element in 'ld_data_base'.

Code:
   ld_data_base = (UB1 *) malloc(21);
   ld_data_ptr = (UB4 *) malloc(3);

I load the element pointers based on some table. Here I've used fixed offsets (6,14):

Code:
   *(ld_data_ptr+0) = (UB4)(ld_data_base);
   *(ld_data_ptr+1) = (UB4)(ld_data_base+6);
   *(ld_data_ptr+2) = (UB4)(ld_data_base+14);

So, I get for example,

*(ld_data_ptr+0) = :00CA3430
*(ld_data_ptr+1) = :00CA3436
*(ld_data_ptr+2) = :00CA343E

Which is fine. Now I malloc some temporary space for something else:

Code:
   data_item = (UB1 *) malloc(1);

and this happens:

*(ld_data_ptr+0) = 0x00CA3430
*(ld_data_ptr+1) = 0x00CA3436
*(ld_data_ptr+2) = 0xE

Why dose malloc-ing 'data_item' cause the value stored in the memory location 'ld_data_ptr+2' to get corrupted?!?! It's as if the last malloc is not respecting the previously allocated space.

Running Borland C++ Builder 5 on Windows XP.

Any help will be GREATLY appreciated!
 
The argument to malloc is size in bytes, while an int is 2 or 4 bytes depending on your system. I think you want:
Code:
   ld_data_base = (UB1 *) malloc(21*sizeof(UB1));
   ld_data_ptr = (UB4 *) malloc(3*sizeof(UB4));
etc :p

(sizeof is a builtin operator that gives the size of a type in bytes)
 
You can also use calloc which takes in two parameters, namely the size of a single element, and how many elements you want. It basically does the same thing as above.

-AntonK
 
Zephyr,

(sizeof is a builtin operator that gives the size of a type in bytes)

Yes indeedy it does! That fixed it. I haven't malloc'ed anything in a while and completely forgot that. Thanks a lot!
 
Status
Not open for further replies.
Back
Top