Thread: Quick question about memory allocation

  1. #1
    Registered User
    Join Date
    Jul 2006
    Posts
    63

    Quick question about memory allocation

    high, i have a function which stores two char*, name and key, into a linked list. This is a different function, which creates the char[] and passes it onto the function which places it into a linked list. My question is if I want to delete name and key later on, will it work. Im thinking that once ive passed the pointer for the char[] to the linked list, how will the function from my linked list class know the size of the strings. Does it work any way, or is there another way to do it?
    Code:
    char* testname;
    char* testkey;
    testname = new char[32];
    testkey = new char[16];

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    My question is if I want to delete name and key later on, will it work.
    Yes, if you use delete[].

    Im thinking that once ive passed the pointer for the char[] to the linked list, how will the function from my linked list class know the size of the strings.
    With respect to delete[], I believe that this size tracking is done behind the scenes. However, with respect to actually using the string, you would need to keep track of the capacity yourself (and the size, if you are not using a null character to mark the end of the portion of the string in use). In fact, you should use std::string or at least some other dedicated string class instead of dealing with raw char*.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Yes, new actually saves the size of the allocated memory in a memory block to where you allocated memory. You can actually get the size with _msize (warning: platform dependant), so I'm guessing that's how delete [] keeps track of it.
    Unless it's a class, delete [] works even on void* pointer.
    Just be sure to use delete [] on arrays and delete on non-arrays. And yes, you're better off with a string class, such as std::string.

  4. #4
    Registered User
    Join Date
    Jul 2006
    Posts
    63
    with delete [], what would be the syntax of that, is it delete [] testarr or delete testarr[]
    im using char[] because im reading and writing memory to another program, and its just easier to have buffers with the bytes i need instead of having to go through a list of functions.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
    delete [] ptr;
    With std::string, you can just call c_str() to get your C-style formated string to work with. As long as you let you string to the memory handling (resize, allocate, etc) you should be fine.

  6. #6
    Registered User
    Join Date
    Nov 2007
    Posts
    14
    This discussion just touched an issue I'm contemplating.

    First, I have an allocation that looks lite this:
    Code:
    ObjectType *mArray = (ObjectType *) new char[sizeof(ObjectType) * iInitialSize];
    Later, I delete it:
    Code:
    delete[] mArray;
    (I use char for allocation because I do not want any objects constructed yet.)

    Does delete[] work as I want to in this case? I'm imagining that there could be a problem because I allocate by char, but try to delete the memory by an ObjectType*.
    Last edited by Araanor; 11-17-2007 at 12:22 PM.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Yes, it works. You can even cast it to void* (because delete takes a parameter of type void* anyway) and it will still work.
    However... It will not work on classes! When allocating and deleting classes, you must not change the type of the pointer.
    And don't use char, use a C++ object instead. Want a string? Use std::string. Want a buffer? Use std::vector.

  8. #8
    Registered User
    Join Date
    Nov 2007
    Posts
    14
    Thanks.

    I'm writing a fast list-class with an array underneath and insertion and deletion in O(1). I'd use the stl vector otherwise.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    You can even cast it to void* and it will still work.
    Perhaps, but it's still undefined behaviour. There is no situation where you may legally apply delete[] to a pointer of a type that is different from the dynamic type of the allocated array. There is only one such situation for normal delete, and that's when the static type is a base class of the dynamic type and the base has a virtual destructor.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    Registered User
    Join Date
    Nov 2007
    Posts
    14
    Undefined, you say.

    What if I do this:
    Code:
    delete[] (char *) mArray;

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > ObjectType *mArray = (ObjectType *) new char[sizeof(ObjectType) * iInitialSize];
    That's just HORRIBLE.

    What's wrong with
    ObjectType *mArray = new ObjectType[iInitialSize];
    - No casting
    - No worrying about whether you got the right type in the sizeof
    - The proper constructors get called.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Still undefined, unless you explicitly call the destructors.

    If you just want a raw memory block to place objects in, don't use new. Use operator new:
    Code:
    void *memory = ::operator new(sizeof(T) * n);
    for(int i = 0; i < n; ++i) {
      new (memory + i * sizeof(T)) T;
    }
    T *ar = static_cast<T*>(memory);
    
    // ...
    
    for(int i = n-1; i >= 0; --i) {
      ar[i].~T();
    }
    ::operator delete(memory);
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  13. #13
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by Araanor View Post
    Undefined, you say.

    What if I do this:
    Code:
    delete[] (char *) mArray;
    Then combined with:
    ObjectType *mArray = (ObjectType *) new char[sizeof(ObjectType) * iInitialSize];
    You're hoping two wrongs make a right?

    You should listen to Salem.

    I'm writing a fast list-class with an array underneath and insertion and deletion in O(1).
    What, so that's just a linked list within a memory pool? Or are you storing items in order in memory contiguously and claiming that is O(1)?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  14. #14
    Registered User
    Join Date
    Nov 2007
    Posts
    14
    Quote Originally Posted by Salem View Post
    > ObjectType *mArray = (ObjectType *) new char[sizeof(ObjectType) * iInitialSize];
    That's just HORRIBLE.
    Sure.

    What's wrong with
    ObjectType *mArray = new ObjectType[iInitialSize];
    - No casting
    - No worrying about whether you got the right type in the sizeof
    - The proper constructors get called.
    Which is the problem, I just wanted a raw memory block.


    Quote Originally Posted by CornedBee View Post
    Still undefined, unless you explicitly call the destructors.
    Oh, the destructors, that's right... Always some detail.

    If you just want a raw memory block to place objects in, don't use new. Use operator new:
    Thank you, that looks better. I just settled for char after reading a stray googled article on new which used char to demonstrate placement syntax.

  15. #15
    Registered User
    Join Date
    Nov 2007
    Posts
    14
    Quote Originally Posted by iMalc View Post
    Then combined with:
    ObjectType *mArray = (ObjectType *) new char[sizeof(ObjectType) * iInitialSize];
    You're hoping two wrongs make a right?

    You should listen to Salem.

    What, so that's just a linked list within a memory pool? Or are you storing items in order in memory contiguously and claiming that is O(1)?
    A linked list would imply links.

    The class uses an array so the objects can be stored in sequence and not be fragmented across memory.
    O(1) is achieved for insertion by inserting items at the end of the list.
    O(1) is achieved for deletion by replacing the deleted item with the last one in the list.

    This stuff with me looking to allocate memory without constructors and other fun headaches is just some smaller optimizations for the heck of it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 04:04 AM
  2. POSIX Threads and dynamic memory allocation
    By PING in forum Linux Programming
    Replies: 1
    Last Post: 04-02-2009, 10:28 AM
  3. Pointer's
    By xlordt in forum C Programming
    Replies: 13
    Last Post: 10-14-2003, 02:15 PM
  4. Memory allocation at runtime?
    By electrolove in forum C Programming
    Replies: 6
    Last Post: 02-05-2003, 11:39 AM
  5. Yet another memory question
    By Dohojar in forum C Programming
    Replies: 5
    Last Post: 03-16-2002, 01:47 PM