Valhalla Legends Forums Archive | C/C++ Programming | malloc function

AuthorMessageTime
touchstone
hi,

i want to know the difference between two

[code]

int main()

{
    int x = 5;


    int *p = malloc(sizeof(int));
    *p = 5;


}

[/code]


question2:

how do i print addresses of a variable in hexadecimal format?
February 1, 2004, 7:38 PM
K
[quote]
how do i print addresses of a variable in hexadecimal format?
[/quote]

If you're using c++, I'm fairly sure the stream insertion operator (<<) prints pointers as hexidecimal as its default behaviour. If it doesn't, you can use the std::hex object from the <iomanip> header.

If you're using c, (which, judging from your malloc statement, is more likely) you simply need to use the appropriate formatter in your printf() statement. I don't know it off the top of my head, but I'd guess %X.
February 1, 2004, 7:45 PM
iago
Question 1:
if you're declaring it as an int, it's a local variable. It's given part of the stack, it's used, and when the function ends it's disappeared.
if you're using malloc(), it's allocating a piece of the program's heap and returning it to your variable. It stays around until either you free() it or your program ends. It's useful for things like returning variables, linked lists, and anything else that you have to control your own memory for.

Question 2:
Assuming you mean C and not C++:
printf("%x", &myvar);

And each variable only has one address, not "addresses"

<edit> lol, K beat me by 7 seconds, and at least he knows how to do it in C++ :)
February 1, 2004, 7:45 PM
UserLoser.
[code]
   int myvar = 14099;
   cout << "Address of myvar: " << &myvar << "\n";
[/code]

:)

Edit: I posted this like 3 seconds after Iago did, then removed it because he posted; but it's back now ;)
February 1, 2004, 7:47 PM
Skywing
The correct, standard way to do it is:

[code]/* C */ printf("%p", (void*)&var);[/code]
[code]/* C++ */ std::cout << (void*)&var;[/code]
February 1, 2004, 7:49 PM
Adron
And seeing how everyone else has already provided great answers, I'd just like to say Thank you! to all contributors.

What a great world this would be if people were always this helpful!
February 1, 2004, 8:29 PM
touchstone
actually, i wanted to know

suppose i am writng

int x = 5;

here, address of the variable x is &x. who is allocating this address ? is it the operating system giving randomly from its stack ?
can a user assign address himself? how?


>>"if you're using malloc(), it's allocating a piece of the program's heap and returning it to your variable "

can you explain a little bit on this statement.



February 1, 2004, 8:34 PM
Adron
Technical details...

In case #1, the memory for the variable is allocated on the stack. The program does this itself, having already been given stack to use by the OS. Simplified example:

[code]
int i;
[/code]

means that

[code]
stackpointer = stackpointer - sizeof(i);
&i = stackpointer;
[/code]

Other variables will typically be assigned sequentially. If you declare

[code]
int j, k, l;
[/code]

then that might mean

[code]
stackpointer = stackpointer - 3 * sizeof(int);
&j = stackpointer;
&k = stackpointer + sizeof(int);
&l = stackpointer + 2 * sizeof(int);
[/code]

Typically, all of the stack variables in a function will be allocated with a single big subtraction at the start of a function. And this is a simplified explanation, ignoring register allocation, etc.


For question #2, the heap is some other memory. It might not be all contigous, and it might grow and shrink over time. Pieces of it can be allocated and freed randomly - as opposed to the stack where you can only allocate and free memory where the stack pointer is pointing. If you allocate a and then b on stack, you can't free a before you free b, but on the heap you can free them in any order.

How this memory is tracked is left to the OS, or run-time libraries to handle. Some compilers will request a large block of memory from the OS, and then use that to serve whatever small mallocs that your code might make. Other compilers will let the OS handle all small allocations. I think the most common implementation of this is to have a linked list of the free / used memory blocks, searching that to find a spot when you malloc and modifying the lists on both malloc and free.
February 1, 2004, 10:02 PM
iago
It should also be noted that doing int i; is done instantly. In fact, it's done at compile time, and the memory is used as if the variable owns it and never has to worry about whether or not another variable is using it.

Using malloc(), on the other hand, is much, much slower. When you do a malloc(), it has to find some un-used memory and declare that it's going to be using it now, so nobody else use it, ok? And furthermore, since we never want 2 variables grabbing the same memory at the same time, there has to be some synchronization within the malloc() call to make sure the memory is only given to your variable and nobody elses. And synchronization takes time.

The bottomline is, malloc() is very slow and should be used with care.
February 1, 2004, 10:59 PM
UserLoser.
[quote author=Adron link=board=30;threadid=5036;start=0#msg42184 date=1075667375]
And seeing how everyone else has already provided great answers, I'd just like to say Thank you! to all contributors.

What a great world this would be if people were always this helpful!
[/quote]

BotDev forum! I'm always helping (Atleast, I think so) :P

Sky: As far as the correct, standard way; this is just what they tell us in school!
February 1, 2004, 11:28 PM
touchstone
hi adron...your explanation is nice.....but i would like to ask about your sample code.
[code]
stackpointer = stackpointer - sizeof(i);
&i = stackpointer;
[/code]


its ok.....but stack( LIFO in data structure) pointer should do the reverse thing.

first it will insert then it will update the pointer.......that is the data structure says...

i am not sure whether your stackpinter follows that data structure rule? does it?

so, i would have been happier to see....

[code]
&i = stackpointer;
stackpointer = stackpointer - sizeof(i);
[/code]

can i think this way ??

N.B i know stackpointer starts from the high memory then goes down to the low memory ( this type of diagram i found in the book)....but it must follow the ordering of insertion i.e first allocate then update pointer.....is not it?
can you give me a web-link which explains various kinds of memory


thanks

February 2, 2004, 3:53 AM
Kp
[quote author=touchstone link=board=30;threadid=5036;start=0#msg42256 date=1075694039]so, i would have been happier to see....
[code]&i = stackpointer;
stackpointer = stackpointer - sizeof(i);[/code]can i think this way ??[/quote]

No. The way you show is incorrect, and produces an unused dword at the address referenced by the stack pointer. Keeping such a dword if it is unneeded is wasteful. Also, consider what would happen in your example if someone then declared an 8 byte member. You would store the current stackpointer (which points to 4 bytes of free memory) into the address for their variable, then subtract 8 bytes. The result is that the upper 4 bytes of their new variable would overlap with the bytes of i. Doing it the way Adron describes handles this situation correctly, as well as avoiding a waste of stack space.
February 3, 2004, 1:21 AM
Adron
Yes, Kp is right. The stackpointer points at the boundary between used and unused memory. You move the stackpointer first, thereby turning "unused" memory into "used" memory. Your way makes room for another 4 byte variable ahead of time, to no real use. Your solution would be correct if either the stack grew upward in memory or if objects were stored downward in memory.

If you draw some sketches of inserting different sized objects, it should all become clear to you.

February 3, 2004, 1:47 AM

Search