Results 1 to 3 of 3

Thread: Dynamic Memory Allocation

  1. #1
    Join Date
    Jun 2011
    Posts
    203
    Thanks
    7
    Thanked 4 Times in 3 Posts
    Qt products
    Qt4
    Platforms
    MacOS X Windows

    Default Dynamic Memory Allocation

    Hi Guys,

    Just trying to figure out how to use dynamic memory allocation. I've got the following program:

    Qt Code:
    1. int main(int argc, char *argv[])
    2. {
    3. QCoreApplication a(argc, argv);
    4.  
    5. char *cText;
    6. cText = new char[5];
    7. cText = "test11111";
    8.  
    9. qDebug() << cText;
    10.  
    11. delete[] cText;
    12.  
    13. return a.exec();
    14. }
    To copy to clipboard, switch view to plain text mode 

    Question is... why does it let me assign a string of more than 5 characters to this memory location?

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,364
    Thanks
    3
    Thanked 5,014 Times in 4,792 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: Dynamic Memory Allocation

    You are assigning a value to the pointer, not to the char array behind the pointer. Your code is equivalent to:

    Qt Code:
    1. int main() {
    2. char *cText = 0; // line #5
    3. char *ptr1 = "test11111"; // line #7
    4. char *ptr2 = new char[5]; // line #6
    5.  
    6. cText = ptr2; // line #6
    7. cText = ptr1; // line #7
    8. delete [] ptr1; // line #11
    9. // cText points to ptr1 and not ptr2
    10. }
    To copy to clipboard, switch view to plain text mode 
    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  3. #3
    Join Date
    Jun 2011
    Posts
    203
    Thanks
    7
    Thanked 4 Times in 3 Posts
    Qt products
    Qt4
    Platforms
    MacOS X Windows

    Default Re: Dynamic Memory Allocation

    Got it to work thanks.

Similar Threads

  1. Replies: 5
    Last Post: 7th February 2013, 02:05
  2. memory allocation problem
    By marc2050 in forum Newbie
    Replies: 7
    Last Post: 23rd May 2011, 09:05
  3. Widget Memory Allocation
    By ArlexBee-871RBO in forum Qt Programming
    Replies: 5
    Last Post: 9th May 2010, 19:51
  4. QDrag : memory allocation
    By kghose in forum Qt Programming
    Replies: 1
    Last Post: 14th August 2008, 22:57
  5. limit memory allocation
    By magland in forum General Programming
    Replies: 10
    Last Post: 23rd March 2007, 09:21

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.