I have a Question about memory usage for C.

This is a discussion on I have a Question about memory usage for C. within the C Programming forums, part of the General Programming Boards category; I am currently working on a Program for my C programming course in college, and i have a very important ...

  1. #1
    Registered User bobthefish3's Avatar
    Join Date
    Oct 2001
    Posts
    22

    Exclamation I have a Question about memory usage for C.

    I am currently working on a Program for my C programming course in college, and i have a very important question that i need an answer to, so that i can decide how to implement my program. here's my question:
    In C (not C++) i need to know what syntax (or code if you will) to create variables (nodes on a linked list) on the heap, instead of on the stack. I know that there is the NEW keyword to create these in C++ at least, but I don't think that NEW is a C keyword. now if NEW is a C keyword, then i will just use that (obviously) along with any of the keywords used for deleting the allocated items once i'm done with them, but if they aren't the keywords i need to know the code i'd need to know to create and destroy heap variables in C (or at least a point in the place to look for the syntax- but in that case it would have to someplace i could look within a day or 2 here- cause this is very time relevant.)
    Any help would be very very very much appreciated, that or just a simple 'there is no way to create heap varaibles in C would do just fine- then i can just implement them on the stack like the rest of the inefficient mongrals < no offense to stack usage- just heap would be nicer and more efficient >

    Now you are probably thinking- who cares if i use C++ syntax if i have a C/C++ compiler that will except it-- very good reason for it, it is a C class, so the instructor will very much frown upon C++ syntax in our programs- in fact they won't except it most likely... hence the dilema.

    Any help, like i say, would be very much appreciated.
    -please do not mess with the incredible radioactive super-fish... thank you.

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Have a look at the Malloc() and free() functions...

  3. #3
    Registered User bobthefish3's Avatar
    Join Date
    Oct 2001
    Posts
    22

    Lightbulb further help

    hey i appreciate the reply, i do know about Malloc, calloc and realloc, but do those only work for dynamic memory allocation on the stack or does it go for the heap memory too (i just have never used them, but i do know about them).
    Is that the only ones that there are though? I haven't read about anything else besides those and that NEW and DELETE that i mentioned at first. Know of anything else?
    -please do not mess with the incredible radioactive super-fish... thank you.

  4. #4
    Registered User oomakoo's Avatar
    Join Date
    Dec 2001
    Posts
    8
    malloc(), etc. allocate on to the heap not the stack.

    there is a function alloca() that allocates on to the stack but that's not what you want is it?

  5. #5
    Registered User bobthefish3's Avatar
    Join Date
    Oct 2001
    Posts
    22

    Cool thanx for the help

    thanx a lot, i think i'll give malloc a shot, just as soon as i figure out how to use it good (never really used it before) o well, can't be hard at all, thanx -
    -please do not mess with the incredible radioactive super-fish... thank you.

  6. #6
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,702
    int *num = (int *)malloc(sizeof(int));

    int nums[] = (int *)malloc(sizeof(int) * 10);//<-- an array of 10 ints

    char *name = (char *)malloc(sizeof(char) * 50); // 50 char string

    SOMESTRUCTURE *myStructure = (SOMESTRUCTURE *)malloc
    (sizeof(SOMESTRUCTURE)); //allocates for 1 SOMESTRUCTURE

    SOMESTRUCTURE *arrayStructures = (SOMESTRUCTURE *)malloc
    (sizeof(SOMESTRUCTURE) * 10); // 10 SOMESTRUCTURE's

    free(num);
    free(nums);
    free(myStructure);
    free(arrayStructures);


    My suggestion is to encapsulate the regular datatypes:

    char *NewString(int num)
    {
    char *c = (char *)malloc(sizeof(char) * num);
    return c;
    }


    So: char *name = NewString(50);

  7. #7
    Unregistered
    Guest
    this isn't C++, you don't have to cast all those calls to malloc

    char *p;

    p=malloc(30);

    that will allocate 30 characters. sizeof char is always 1.
    it is guaranteed.

    you also need to check the return value of malloc to make sure the memory was allocated. It returns NULL on error, and a pointer to the memory location allocated if there was no error.

    you also need to check the return value of realloc(), but you need to use a temp variale to use it because you will lose your memory and create a memory leak if you don't... that is all I have time to write. Bye.

  8. #8
    Registered User oomakoo's Avatar
    Join Date
    Dec 2001
    Posts
    8

    Smile

    IMHO, while not strictly necessary, casting the return from malloc() is good programming practice and should always be done - there is no reason not to do it. And getting into the habit of using sizeof() for all calls to malloc(), whether the size is guaranteed or not, is also a Good Thing (TM).

    I've found that using good programming practices and switching on compiler warnings and fixing them leads to better programs than just reducing the amount of typing that you do.

  9. #9
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,702
    Well, my compiler whines and won't compile without all the casts.

    Anyway that's not what's important.

    The main issue is as to how/where/when to create and destroy variables. It makes a big difference if you're using a function that allocates for and returns a string, being called hundreds or thousands of times a day in a real system that leaks 100 chars each call simply because the programmer using the module doesn't know to free the memory since he didn't allocate it himself, or else he DID allocate it and so deallocates locally but not with respect to the function which also created a chunk of memory!

    So you need a system of checks and balances .

    A massive memory scheme sounds like a headache, and if your not careful, it may turn out just that. But if you keep to one methodology, stick with it and make it a policy to communicate well with your collegues so that any other such 'ignorances' are avoided.
    Code:
    bool flip(bool value)
    {
        return std::pow(std::exp(1), std::complex<float>(0, 1) 
        * std::complex<float>(std::atan(1)*(1 << (value + 2))))
        .real() < 0;
    }

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    IMHO, while not strictly necessary, casting the return from malloc() is good programming practice and should always be done - there is no reason not to do it.
    You have this backwards. You should NOT provide the cast, and then turn on all your compiler warnings. Since in C it is not necessary to typecast, this helps you find warnings for when you screw up. This is the reason to NOT typecast. If you typecast, and you're doing something wrong, your compiler won't complain because you've cast, thus, you may not see the potential error.

    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    Registered User oomakoo's Avatar
    Join Date
    Dec 2001
    Posts
    8
    Originally posted by quzah


    You have this backwards.

    I don't think I do. malloc() will always return a void *. If you tell the compiler what you think it should be cast to (by explicitely casting) then the compiler can tell you whether you are right or not.

  12. #12
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    With casting you might code some thing like

    /* #include <stdlib.h> */

    int main(void)
    {
    char* s = (char*)malloc(100, 100);
    return 0;
    }

    Ofcourse this won't compile in c++ and c compiles will
    warn about it if you set the warnings high enough.

  13. #13
    Unregistered
    Guest
    No I am sorry, but Quzah is correct. Omitting the cast is not just to save typing, and if you compiler will not compile the code without the cast then it is not an ANSI C Compiler, perhaps you have C++ mode on? In addition, omitting the cast does, as Quzah said, allow the compiler to be more accurate in what errors/warnings it provides you. There is an implicit cast from void * to whatever pointer you are assigning the return value of malloc to, so therefore it is not necessary. Also using sizeof all the time is /not/ a good programming practice because it wastes memory and time. If you know that the size of char is guaranteed to be 1, (which the ANSI Standard guarantees to us) then why waste CPU time calculating the value of a
    constant? Not only do you waste time by calculating the constant value of the size of char, you also waste more time multiplying it by how many elements you want.

    To reiterate again(so it gets through your thick skull) consider the following psuedocode examples.

    size=sizeof(char);
    final=size*elements wanted;
    allocate(final);

    vs.

    allocate(elements_wanted);


    Hmm... I wonder which code is more efficient? Mine uses less memory /AND/ CPU cycles. The goal of programming should be to do whatever you are trying to do in the most efficient way possible, so therefore my way is more correct and you have a lot more learning to do.

  14. #14
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    With casting you might code some thing like



    /* #include <stdlib.h> */



    int main(void)

    {

    char* s = (char*)malloc(100, 100);

    return 0;

    }



    Ofcourse this won't compile in c++ and c compiles will

    warn about it if you set the warnings high enough.

  15. #15
    Unregistered
    Guest
    I don't know what compiler you are using Nick.

    Try running the following code through
    gcc like so

    gcc -W -Wall -pedantic -ansi

    which turns on the highest warning levels

    #include <stdlib.h>

    int main()
    {
    char *p;

    p=malloc(30);
    if(p==NULL)
    {
    printf("Oops, not enought mem.");
    return EXIT_FAILURE;
    }

    free(p);
    return 0;
    }

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer memory question
    By Edo in forum C++ Programming
    Replies: 5
    Last Post: 01-21-2009, 02:36 AM
  2. Memory allocation question
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 10:41 PM
  3. Another Question...memory allocation
    By quickclick330 in forum C Programming
    Replies: 4
    Last Post: 12-12-2007, 03:25 PM
  4. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 12:57 AM
  5. [C] Trouble with memory usage
    By BianConiglio in forum Windows Programming
    Replies: 1
    Last Post: 09-28-2004, 08:57 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21