deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A segmentation fault is when you try to access memory outside of your address space, or protected memory that you don't own. It's nearly always the result of a bad pointer or array index value, so checking those values should be your first line of attack.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but why we don't use printf()?

Allow me to make an enlightening comparison from my own stdio library. The back end to putchar() is fputc(), which totals in at 22 lines of code. fputs() is built on top of fputc() and is all of 6 lines.

The guts to printf() are pushing 1,000 lines of code.

print() is a very heavy function that does a lot of work. If all you need to do is print a string or character directly, there are simpler functions that do this without any extra rigmarole.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Bit representation of 12 is 00000000 00000000 00000000 00001100.

12 has nothing to do with this. You may have typed 12, but scanf() read the numeric value of '1' and stored it in the first byte. Note also that depending on your system's endianness, the "first" byte may be either the most significant or least significant since scanf() is working directly with memory addresses and not endian-corrected values.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That's what you get when you lie to scanf(). Assuming 4 byte integers, a looks like this (the question marks mean an indeterminate value):

[?][?][?][?]

Now when you pass the address of a into scanf() and say that it's a pointer to char, scanf() will do exactly what you asked and only fill in the first byte:

[d][?][?][?]

Now when you pass a into printf() and try to get the integer value, you get garbage because the remaining 3 bytes are still uninitialized. It's really no different in terms of undefined behavior than if you just did this:

int a;
printf("%d", a);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

what is size_t in this??

size_t is a typedef representing the type returned by the sizeof operator. It's very often used as the type for array indices because the maximum value of size_t will never be less than the potential number of indices in any array.

can't we take it as int because we are just passing the size which is an integer??

Yes, you can use int instead.

and could you please explain this part too??

When you type a backspace character, both the last actual character stored in the string and the last displayed asterisk need to be removed. fputs("\b \b", stdout) will handle the latter by first printing a backspace (which isn't destructive, it only moves the cursor), then one space character to overwrite the character being removed, and finally another backspace to place the cursor in the correct position.

Removing the last character from the string is even easier because all you need to do is decrement the index and the character will be overwritten on the next iteration. But there's one edge case where the index is already 0, and you don't want it to go negative or bad things happen.

These two tasks work together to keep both the password string and the display in sync when you type a backspace.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Since you've sidestepped the command shell's conveniencies like being able to edit your input before sending it to the program, that functionality needs to be duplicated within your program. In this case that means recognizing and handling the any special characters that the shell normally handles for you:

#include <stdio.h>
#include <conio.h>

char *get_password(char *buf, size_t n)
{
    int done = 0;
    size_t i = 0;

    while (!done && i < n - 1) {
        int ch = getch();

        switch (ch) {
        case '\r':
            /* Convert CRLF to a newline */
            putchar('\n');
            buf[i++] = '\n';
            done = 1;
            break;
        case '\b':
            /* Roll back a previous character */
            fputs("\b \b", stdout);
            fflush(stdout);

            /* Don't underrun the buffer */
            if (i > 0)
                --i;

            break;
        default:
            putchar('*');
            buf[i++] = (char)ch;
            break;
        }
    }

    buf[i] = '\0';

    return buf;
}

int main(void)
{
    char buf[BUFSIZ] = {0};

    fputs(get_password(buf, sizeof buf), stdout);

    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

any other book same as the introduction to algorithms ,deceptikon

I used to collect programming books, but I've since cleaned house and sold the majority of them. However, the data structure and algorithm books I still keep on my bookshelf related to C are:

  • Algorithms in C (Robert Sedgewick)
    The material is first class, but the code is absolute shit. However, I firmly believe that one can learn a lot by fixing the bugs.

  • Practical Algorithms (Andrew Binstock & John Rex)
    I have this one more for the code than anything. It's not great code, but not bad either, and I imagine it would be an informative book for a beginner.

  • Practical Algorithms in C++ (Bryan Flamig)
    This is my favorite on algorithms. Great book.

  • Practical Data Structures in C++ (Bryan Flamig)
    This is my favorite on data structures. Fantastic book.

  • Data Structures and Algorithms in C++ (Adam Drozdek)
    I actually haven't read this one... I had an older version that focused on C and upgraded to the latest edition in C++. I just haven't had the time to work my way through it. But from what I've seen, it's pretty decent.

I'm actually not a huge fan of CLRS, mostly because I don't find its contents inspired at all, which makes reading it boring. But if you're not familiar with the subject, CLRS is definitely the most recommended book.

If you read and understand this book, you will be very …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'll answer your comments directly:

// Should I malloc memory for ptr_ex here before assigning values to it???

Yes. An unintialized pointer is not a pointer to usable memory, you must first point it to memory that you own either through dynamic allocation or through the address of an existing variable.

Though in this case you don't need a pointer. You can simply create an instance of the structure and pass its address to myfunc().

//Can I directly deference the values below???

Provided that myptr points to a valid object and the object has been initialized with non-garbage values, yes.

or should I malloc memory for *myptr also???

No. The assumption here is that the calling function owns the memory for this pointer and has set everything up properly for you to use it without worrying about managing memory.

I_m_rude commented: excellent explaintion... +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

does that means that order in which i write the structures elements matter to calculate the offset and hence size changes?

Yes. My personal preference is to order members in a way that makes intuitive sense at a higher level than padding and alignment, but that's just a general guideline. I've been known to optimize the organization of my structures when the situation warranted it. ;)

also 3 bytes are free here.. isnt it memory wastage though small?

This is one of many places where you'll encounter the speed vs. space tradeoff. At the cost of a few bytes, the performance can be improved by a statistically significant amount.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how performance is increased?

Values can be loaded into memory and registers more quickly when they're suitably aligned. Otherwise the system might have to calculate an offset from a native boundary to get to the correct address.

are structure elements location in memory contiguous?

Barring padding, yes.

if yes, in this case then there is free memory blocks after char variable as size is greater than individual sum?

In this case I'd wager that there are 3 bytes of padding after q so that w is properly aligned on a word boundary. So the structure looks like this in memory:

[q][?][?][?][w][w][w][w]
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What does the tree look like?

Why should that matter? As long as it's a valid binary search tree, the algorithm won't change depending on how the tree looks.

Can anybody share the algorythm to perform inorder traversal of a binary search tree using parent node(without stack or recursion)

As long as you save the encountered node, it's a relatively simple matter of using the value of the previous node to determine where to go next. For example (pseudocode):

while it <> null
    if prev = it.parent
        prev = it

        if it.left <> null
            it = it.left
        else
            visit(it)

            if it.right <> null
                it = it.right
            else
                it = it.parent
        endif
    else if prev == it.left
        prev = it
        visit(it)

        if it.right <> null
            it = it.right
        else
            it = it.parent
    else if prev = it.right
        prev = it
        it = it.parent
    endif
endwhile
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Members of a structure may be aligned to certain byte boundaries to improve performance or if the platform simply doesn't allow an object of a certain type to begin at any byte. Also, and partially to facilitate alignment, there may be padding between members of a structure or at the end of the structure.

So unless you go out of your way to pack a structure (using non-portable methods), its size will likely be more than the sum of its members' sizes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here's a very simple example of what I was talking about:

#include <ctime>
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>

using namespace std;

time_t make_time(tuple<int, int> new_time)
{
    time_t now = time(0);    // Find the current time
    tm *info = gmtime(&now); // Convert it to calendar info

    // Update the minute and second
    info->tm_min = get<0>(new_time);
    info->tm_sec = get<1>(new_time);

    // Convert back into a time_t (fixing errors in the process)
    return mktime(info);
}

tuple<int, int> parse_time(const string& s)
{
    istringstream iss(s);
    int min, sec;

    // Naive parsing, assumes the string is valid
    iss >> min;
    iss.get();
    iss >> sec;

    return make_tuple(min, sec);
}

int main()
{
    time_t time_in, time_out;
    string s;

    cout << "Enter player time-in between 08:00 and 17:00: ";
    cin >> s;
    time_in = make_time(parse_time(s));

    cout << "Enter player time-out between 08:00 and 17:00: ";
    cin >> s;
    time_out = make_time(parse_time(s));

    cout << "Play time was " << difftime(time_out, time_in) << " seconds\n";
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, but it's not built in to the language or standard libraries.

Actually, it is as of C11. Though the trick with the latest standard is finding an implementation of it. Hopefully C11 will be more widely adopted than C99. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Oddly enough, I think I'm in favor of option 2. Though there would definitely need to be a way to hide excess numbers of comments. It's rare currently, but if the reputation system is used more often because of this feature, that kind of thing might become more common.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Our permission/ranking system isn't strictly by post count. Specifically, the difference here is between a Newbie Poster and a Community Member. Once you've reached the threshold of either 15 reputation points or 5 posts plus 5 days since joining, your rank will automatically go from Newbie Member to Community Member. At that point you'll have all permissions allowed for Community Members, including the ability to send private messages.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

wth, why would someone want to do that

Intimidated by my sheer awesomeness, I suppose. :D

zeroliken commented: probably, likely ;) +9
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i wonder how did u become administrator without having any basic knowlege of c language ?

The two are unrelated. But if you want to discuss aspects the C language or standard library, I'll be happy to school you in a debate.

now just get lost from daniweb and stop banning users form daniweb

I only ban people who violate Daniweb's rules often enough to deserve it, and I can justify each and every one of them. I'm curious what your problem is, or who you really are since it's unusual for there to be such animosity given only 3 posts in this thread. Are you one of the rule breakers I've banned?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My understanding of the C language is that the same identifier cannot be reused.

That's correct, but only within the same name space (not the same as a C++ namespace). There are five listed name spaces in C:

  1. Label names (such as cases and goto labels).
  2. Structure, union, or enum tags.
  3. Structure or union members.
  4. Typedef names;
  5. Everything else.

With those name spaces in mind, it's easy to understand why the following is legal:

typedef struct foo { int foo; } foo;

In your code, the typedef error and the macro error are in different name spaces (the typedef falls under #4 and the macro under #5), so there's no direct conflict.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Actually, this is very easily done...that is if you did some basic C-language based I guess- programming including pointers. In C, since you can use pointer arithmatic on a pointer that you have malloced initially. So, if you are to say make a pooled memory-or given a memory space in which you are allowed to access- do arithmatic pointer and divide up the memory. Use strucs and/or headers to make things simpler. If you are given an "initialized" memory space as a form of an array, than it is easier. Array indexes also satisfies the arithmatic, so you can put -1 or other magic number in an array to indicate its empty, and work your way out from there on.

It's easier than that if the system allocation options are similar enough to malloc() to facilitate a thin wrapper. For example, I wrote an implementation of the standard library that defines malloc as such:

/*
    @description:
        Allocates space for an object whose size is specified by size.
*/
void *malloc(size_t size)
{
    uintptr_t mem = (uintptr_t)_sys_heapalloc(__sys_heap, size + sizeof(size_t));

    *(size_t*)mem = 0; /* General alignment */
    mem += sizeof(size_t);

    return (void*)mem;
}

Where _sys_heapalloc() is nothing more than a portability wrapper around the Win32 API's HeapAlloc():

/*
    @description:
        Allocate the specified number of bytes from the specified heap.
*/
void *_sys_heapalloc(_sys_handle_t heap, unsigned bytes)
{
    return HeapAlloc(heap, 0, bytes);
}

Barring initialization and teardown of the __sys_heap object in the C runtime code, that's …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

zeroliken you are wrong
Its not the right answer

Then what do you think is the right answer? The sequence you showed is clearly 5^n at every step. If the 5th step isn't 3125 (5^5) then either you didn't provide sufficient information about the sequence to reach the next number, or you don't realize that the answer is 3125. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

f(&i) has no effect on i.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just for the record, when someone talks about occurrences they almost never mean combinations. As for how this works, it recursively builds a tree that breaks down the string, swaps elements, and recombines them to produce combinations.

When you have an algorithm you don't understand, the best approach is to either step through a small data set in a debugger or on paper and draw out what happens to the data. For example, you can get a good test run of this algorithm by typing "abc".

Don't expect someone to be around to explain everything to you, a good programmer's best weapon is the ability to disect code, trace through it, and methodically figure out how it works without any help.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Nobody is going to do your homework for you, and calling it a competition isn't going to fool the vast majority of us. Please read our rules, provide proof of effort, ask some questions, and we'll help you do it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
#include <stdio.h>

#define MAX 5

void store(int a[], int i, int n);

int main(void)
{
    int a[MAX];
    int i;

    store(a, 0, MAX);

    /* Test the result */
    for (i = 0; i < MAX; ++i)
        printf("%d ", a[i]);
    puts("");

    return 0;
}

void store(int a[], int i, int n)
{
    if (i == n)
        return;

    do {
        fflush(stdin); /* Placeholder for a better solution */
        printf("Enter number #%d: ", i + 1);
        fflush(stdout);
    } while (scanf("%d", &a[i]) != 1);

    store(a, i + 1, n);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not in C or C++. Index values must be positive.

As long as the index refers to some location in the array's boundaries, indices may be positive or negative. For example:

int a[] = {1, 2, 3, 4, 5};
int *p = a + 2;

printf("%d\n", p[-1]); /* Perfectly legal and portable! */

Whether this is useful or not is up for debate. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

While it may be all in good fun, I don't see any reason to hide the numbers or the titles. Especially given that it's public knowledge anyway, if you're willing to search through our members to figure it all out (which would be tedious and annoying). I suspect we have someone at each tier.

So here are the post counts and titles as they stand right now:

25:    Light Poster
50:    Junior Poster in Training
100:   Junior Poster
200:   Posting Whiz in Training
300:   Posting Whiz
400:   Posting Pro in Training
500:   Posting Pro
600:   Practically a Master Poster
700:   Master Poster
800:   Practically a Posting Shark
900:   Posting Shark
1000:  Veteran Poster
1200:  Nearly a Posting Virtuoso
1500:  Posting Virtuoso
2000:  Postaholic
2200:  Nearly a Posting Maven
2500:  Posting Maven
3000:  Posting Sensei
3200:  Nearly a Senior Poster
3500:  Senior Poster
4000:  Industrious Poster
5000:  Posting Expert
6000:  Posting Genius
7000:  Posting Sage
8000:  Posting Guru
9000:  Posting Prodigy
10000: Most Valuable Poster

These numbers and the titles given at each number are subject to change at any time, which makes the list less helpful than you might think because by the time you reach the next tier everything may have changed. Also note that these are the default titles. If you choose to apply a custom title, all bets are off. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

At least we're closer to completion of this feature, if the read status is only inaccurate from the homepage but works from forums and categories. I'll be doing training next week, but will definitely make some time to look into this (hopefully!) final piece.

~s.o.s~ commented: Good job! :) +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You don't have a prototype for gem(), you're not passing the required arguments, getch() requires conio.h to be included, and relying in implicit int for main()'s return type is poor practice give that this feature was removed in C99.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Open a file stream using fopen(), then call fprintf() instead of printf(). Alternatively, you could redirect stdin into a file, but I don't get the impression that this is what you want.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here is another link. I can't really help you too much as I'm not familiar with this data structure. It seems fairly specialized.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Did you read the referenced tutorial as well?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This was the first hit on google.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ignoring the questionable use of goto here, you never initialize or update the value of a, yet that value is assigned to j when a number is not prime. That raises red flags. If the purpose of this algorithm is to print the primality of every number from [1,N] then there's really no point in updating j at all.

So let's try this a different way. Use a simple boolean flag, initialized to true, and set it to false if the primality check fails. Then after that check, test the flag and display success if it's still true:

#include <iostream>
using namespace std;

int main ()
{
    int N;
loop:
    cout << "Please enter a positive integer or 0 to quit: ";
    cin >> N;
    if (N==0) return 0;
    else {
        while (N<1)
        {
            cout << "Please enter a positive integer or 0 to quit: ";
            cin >> N;
            if (N==0) return 0;
        }
        for (int j=1;j<=N;j++)
        {
            if (j==1||j==2) {cout << j << " is prime."  << endl; cout << "\n";}
            else
            {
                bool isprime = true;

                for (int i=2;i<j;i++)
                {
                    if (j%i==0)
                    {
                        cout << j << " is not prime.\nIt is divisible by " << i << "." << endl;
                        cout << "\n";
                        isprime = false;
                        break;
                    }
                }

                if (isprime) {cout << j << " is prime." << endl; cout << "\n";}
            }
        }
        goto loop;
    }
    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if(root==NULL)

has no meaning at all...

It has meaning, it's just a pointless meaning. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is it possible to add a new category? Yes or No?

If YES we dicussed about it or NO I will click Solved and more on.

Yes, it's possible. Either Dani or I would have to do it on the code/database side, but it's certainly possible. Whether adding categories when Daniweb is already fragmented (some would say overly fragmented) is another matter.

In the past we've gone with the petition route. If you can find enough people to petition for the addition of a new forum or category, we can consider it. The problem is that we don't want a lot of forums with low activity, so there needs to be sufficient demand before the addition can be justified.

Another thing to consider is that the tagging system is the intended future. With the design of the new system we were writing it with an eye toward making tags more of a key player (somewhat similar to Stack Overflow) than the current forum hierarchy.

LastMitch commented: Thanks for answering my question! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

factorial(x--,y*z,z++);

You're passing the current value of x to factorial(), recursion never stops and you experience a stack overflow.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I want to get output which same as the input.

Then use strings. Floating-point is inherently imprecise due to the limitations of the machine and gains or losses from rounding. It's unreasonable to expect the internal representation of a value to be exactly what the user typed for input, especially given that printf() does its own rounding when converting that value back to a string. In this specific case you can normalize the input and output by forcing a precision to the input:

printf("%.2f\n", n);

But that doesn't help if the input changes to use 3 characters past the radix, you'd see the same problem in reverse.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But sir according to me string literals can be modified

According to you? How does your authority override the official language standard? I recognize that you might use a compiler that doesn't store string literals in read only memory, but that doesn't make attempts to modify them any less wrong.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Freeing a NULL pointer will cause the program to crash.

That's incorrect. Calling free() on a null pointer is guaranteed to be a no-op.

teachMyself commented: So when you say it is a no-op, do you want me to still use it here onwards or I shouldnt.? +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Perhaps someone can describe this better!

C++ performs name mangling to enable the overloading feature. If you declared the entities with C linkage (by compiling them as C) and tried to link with the same entities that have C++ linkage (by compiling them as C++), there won't be a match due to mangling. So while the names would be declared, and appear to be defined in the source code, they wouldn't actually be defined.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What do you know about binary coded decimal representation? That appears to be what the function's intended purpose is, which is a bigger issue than the type of pBcdBin.

But the type of pBcdBin is a pointer to zero or more bytes (that's what uin8_t represents here), where neother the pointer itself nor the bytes may be changed, they're both immutable. Technically you could simplify the function signature like so:

short BcdBin(unsigned char *pBcdBin);

This takes advantage of the fact that short int is at least 16 bits and unsigned char is at least 8 bits. The const qualifiers probably aren't necessary, but they make your life easier by enforcing immutability inside the function (ie. stop you from changing them accidentally).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Because I couldn't install netbeans at home so I couldn't try.

So NetBeans is the only C++ implementation? I see you tried sooo hard. :P

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What ever happened to reading the manual?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but when i asked you the question abonu changing the constant through the pointer, then you said that is undefined.

Undefined means the C standard places no restrictions on behavior. This is obviously quite different from disallowed, where the standard says clearly that you aren't allowed to do something. The former means anything could happen and you need not be warned in any way, while the latter will result in a diagnostic message.

So this means i can't do that thing as it is undefined totally. So it's not correct to do that.

It's not correct, but you can still do it.

int a=10;

is it compile time constant ? how ?

10 is a compile time constant, a is not.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is the value of EOF in c...?

The value of the macro EOF is completely irrelevant because it's an internal standard library flag that has no meaning to either you or the outside world. Though nitin1 is correct that it's usually defined as something like -1.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not really. See function Sort() in the code below

I stand corrected. Bubblesort is still painfully inefficient though, and even more so with linked lists due to the excessive chasing of pointers. I'll stand by my original recommendation that a streaming friendly algorithm is far better suited to sorting a linked list than the usual suspects in array sorting.

Of course, a better general solution is to modify the insertion algorithm to keep the list sorted. That way a separate (inefficient) sorting step is unnecessary and the time needed to sort the list is amortized over all of the insertion operations.

I_m_rude commented: full of confidence!! awesome +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If the length of your list is large enough that a faster sort is warranted, then a linked list is the wrong choice of data structure. But I'll mention two things:

  1. Bubble sort is a bitch with linked lists. Insertion sort is much easier to implement.

  2. Following that line of thought, any algorithm that can run with streamed data is well suited to linked lists, so my first suggestion of a faster sort would be merge sort.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Constant means it cannot be changed, but you've already learned how to change a const qualified value through a pointer, right?

As pertains to this issue, compile time constant basically means that the constant can be used as the size of an array or as a case label in a switch statement. If you can't do either of those two things, it's not a compile time constant.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can anyone tell me whether we can use const variables for case ...

No, case labels must be a compile time constant. In C the const keyword doesn't make the variable truly constant, it just makes it read-only under normal circumstances. Turbo C might offer a extention to support non-constant labels, but you can't rely on that outside of Turbo C.

likewise if we use this const variable as array index during initialisation...would it work...

No. This works in C++ because C++ changed the semantics of const, but not C.

can anyone explain ...at what time memory is allocated for variables...

It depends on where you declare the variable, but for the most part variables are stored on the stack at runtime.