Adobe Interview Question
Computer ScientistsYour code doesnt work if the variables are not of integer types.
#define swap(type,a,b){type c = a; a = b; b=c;}
We can use this macro and pass the type as an argument.
e.g. swap(int,a,b) will swap two integers a and b
I think you can also do this if you don't want to have to pass the type:
#define swap(a,b){if (!a) { a = b; b = 0;} else if (!b) {b = a; a = 0;} else { a = a^b; b= a^b; a = a^b;}}
Actually, my method does not work with structs. It would work with pointers and any other primitive. However, kkishore's version does give you type safety, so it's probably the best.
3)how free remembers how many bytes to delete
Its implementation dependent. In Linux, malloc allocates 4 bbytes more than the actual allocation size. These 4 bytes are 4 bytes before the allocated pointer. And they store the amount of memory allocated by malloc. So when free(ptr) is called, the compiler goes 4 bytes before ptr and reads the amount to be deleted.
This could be totally different for other OSs. Something like maintaining a table of allocations with pointer allocated as key by the heap manager. Or storing the number of bytes allocated as the first few bytes of allocation. HTH
When you call malloc(), you specify the amount of memory to allocate. The amount of memory actually used is slightly more than this, and includes extra information that records (at least) how big the block is. You can't (reliably) access that other information - and nor should you :-).
When you call free(), it simply looks at the extra information to find out how big the block is.
typically this is stored at the end of the block but is highly machine dependent as in some machines this is mapped at some other location.
int sprintf ( char * buffer, const char * format [ , argument , ...] );
- aditya.bokaro August 08, 2011#define is handled by preprocessor, typedef by compiler
#define has no scope control
some things cannot be done by #define like intelligent declaration of pointers.
typedef int* int_p1;
int_p1 a, b, c; // a, b, and c are all int pointers.
#define int_p2 int*
int_p2 a, b, c; // only the first is a pointer!