简体   繁体   中英

Dynamic memory and pointers

I'm making a program that has to allocate memory for a certain type and it has to store the size of the data and also the size of the data I passed to it. So if I allocate 8 bytes I need to store the size of memory in the first 4 bytes and store the remaining size in the other 4 bytes. I think this is referred to has headers, but I'm still fairly new to C. All I have right now is the allocated space, how do I store values in that?

int * mem_start_ptr; //pointer to start off memory block
    int data; 
    data = &mem_start_ptr; 
    mem_start_ptr = (long *)malloc(sizeof(long)); //reserver 8 bytes

First of all, sizof(long) is implementation specific and is 8 bytes on 64bit Linux, yet 4 bytes on Windows and 32bit Linux, AFAIK. Use malloc(8) if You want to allocate 8 bytes explicitly. Although, since You want to store int , it seems, use malloc(sizeof(*mem_start_ptr)) . Also, don't cast the return value of malloc , it is redundant in C and can even hide bugs. Now, to store those two 4 byte values:

/* for the first one. Let's use 42 */
*mem_start_ptr = 42;
/* for the second one. Let's put the value of of some variable here */
*(mem_start_ptr + 1) = int_variable;

You should read about pointer arithmetic. And also probably about arrays. Google is Your friend. Also, no idea what this part in Your code is for. As it does not do what You probably expect it to do :

int data;
data = &mem_start_ptr

In the end, I'd rewrite Your code like this:

int *mem_start_ptr;
mem_start_ptr = malloc(sizeof(*mem_start_ptr));
*mem_start_ptr = your_1st_4bytes;
*(mem_start_ptr + 1) = your_2nd_4bytes;

Don't forget to free() it after it is no longer needed. Also, I did not shot it here, but also don't forget to check for NULL , as malloc() returns that on failure.

Yet again - read about pointer arithmetics. Google is Your friend ;]

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