delete array - get error

This is a discussion on delete array - get error within the C++ Programming forums, part of the General Programming Boards category; I am using test code listed below. it's giving me a segmentation fault at the delete []ch; line. #include <iostream.h> ...

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    3

    delete array - get error

    I am using test code listed below.
    it's giving me a segmentation fault at the delete []ch; line.

    #include <iostream.h>
    int main()
    {
    char* ch = new char[3];
    ch = "ts";
    cout << "ch is: " << ch << endl;
    cout << "deleting heap" << endl;

    // here is where the problem is.
    delete []ch;

    cout << "deleted" << endl;
    cout << "creating new array" << endl;
    ch = new char[3];
    cout << "setting value" << endl;
    ch = "ab";
    cout << "ch is: " << ch << endl;
    return 0;
    }

    Do you know why I'm getting this error?
    Any help would be appreciated
    Thanks!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,484
    You're not deleting the same pointer you created with new

    char* ch = new char[3];
    ch = "ts"; // this overwrites the pointer
    delete []ch; // BOOM!


    char* ch = new char[3];
    strcpy(ch,"ts"); // copy the string to where ch points
    cout << "ch is: " << ch << endl;
    cout << "deleting heap" << endl;
    delete []ch; // this should work
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    3

    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting other processes class names
    By Hawkin in forum Windows Programming
    Replies: 3
    Last Post: 03-20-2008, 04:02 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  3. using c++ in c code
    By hannibar in forum C Programming
    Replies: 17
    Last Post: 10-28-2005, 09:09 PM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. Stupid compiler errors
    By ChrisEacrett in forum C++ Programming
    Replies: 9
    Last Post: 11-30-2003, 04:44 PM

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