• Welcome to Valhalla Legends Archive.
 

malloc function

Started by touchstone, February 01, 2004, 01:38 PM

Previous topic - Next topic

touchstone

hi,

 i want to know the difference between two



int main()

{
    int x = 5;


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


}




question2:

 how do i print addresses of a variable in hexadecimal format?

K

#1
Quote
how do i print addresses of a variable in hexadecimal format?

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.

iago

#2
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++ :)
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


UserLoser.

#3

   int myvar = 14099;
   cout << "Address of myvar: " << &myvar << "\n";


:)

Edit: I posted this like 3 seconds after iago did, then removed it because he posted; but it's back now ;)

Skywing

#4
The correct, standard way to do it is:

/* C */ printf("%p", (void*)&var);
/* C++ */ std::cout << (void*)&var;

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!

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.




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:


int i;


means that


stackpointer = stackpointer - sizeof(i);
&i = stackpointer;


Other variables will typically be assigned sequentially. If you declare


int j, k, l;


then that might mean


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


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.

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.
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


UserLoser.

Quote from: Adron on February 01, 2004, 02:29 PM
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!

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!

touchstone

hi adron...your explanation is nice.....but i would like to ask about your sample code.

stackpointer = stackpointer - sizeof(i);
&i = stackpointer;



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....


&i = stackpointer;
stackpointer = stackpointer - sizeof(i);


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


Kp

Quote from: touchstone on February 01, 2004, 09:53 PMso, i would have been happier to see....
&i = stackpointer;
stackpointer = stackpointer - sizeof(i);
can i think this way ??

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.
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

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.