Memory Fragmentation in C++

拈花ヽ惹草 提交于 2019-12-14 03:28:18

问题


I want to use malloc()/new to allocate 256KB memory to variable m. Then, use m to store data such as strings and numbers. My problem is how to save data to m and retrive them.

For example, how to store int 123456 in offsets 0 to 3 and read it to variable x? Or store "David" string from offset 4 to 8(or 9 with \0) and then, retrive it to variable s?


回答1:


You can store an integer by casting pointers.

unsigned char *p = new unsigned char[256 * 1000];
*(int *) p = 123456;
int x = *(int *) p;

This is a terrible idea. Don't worked with untyped memory, and don't try to play fast and loose like you do in PHP because C++ is less tolerant of sloppy programming.

I suggest reading an introductory C++ textbook, which will explain things like types and classes which you can use to avoid dealing with untyped memory.

Edit: From the comments above, it looks like you want to learn about pointer arithmetic.

Don't use pointer arithmetic*.

* unless you promise that you know what you are doing.




回答2:


Please read my comment, I think you need to know more about C and low level native programmng.

Is there a specific application for that format?

to assign a structure to memory you can do somethinglike

struct my_format{
    int first;
    char second[5];
};

int main()
{
     struct my_format *mfp=
          malloc(sizeof(struct my_format));
     mfp->first=123456;
     free(mfp);
}

or whatever this doesn't deal with memory specifics (IE exact positions of vars) vur doing so is just plain bad in almost all ways.



来源:https://stackoverflow.com/questions/9524771/memory-fragmentation-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!