# "C" malloc problem! Help!

Discussion in 'Computer Science & Culture' started by superluminal, Feb 2, 2006.

Not open for further replies.
1. ### superluminal.Registered Senior Member

Messages:
10,717
Ok, I have this problem.

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!

3. ### ZephyrHumans are ONERegistered Senior Member

Messages:
3,371
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

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

5. ### AntonKTechnomageRegistered Senior Member

Messages:
1,083
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