runtime error with dynamically allocated memory to hold C++ string

I have made a program that dynamically allocates memory to hold several c++ string. There were no problems during compile time. But during runtime I always get a message box telling me that my program has stopped running.

I've observe that when I try to change or print the contents of the 2nd up to the last string element I always get that runtime error.

I have pasted the code of my program here. I wish you can compile it then try running it to check if you dont get any runtime errors.

Here the code of my program :(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
    string *numbers = NULL;
    unsigned n=2, i=0;

    //allocating
    numbers = (string*) realloc (numbers, n * sizeof(string));

    if (numbers==NULL)
    {
        puts ("Error (re)allocating memory");
        exit (1);
    }

    for(i=0; i<n; i++)
        numbers[n-1] = "kingkoy ";


    free(numbers);
    return 0;
}
The problem is that you are not constructing string objects --only creating the space for them.

Since this is C++, you should be using new and delete:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
...

int main()
{
    unsigned n=2;

    string *numbers = new (nothrow) string[ n ];

    if (numbers == NULL)
    {
        cerr << "Error allocating memory" << endl;
        return 1;
    }

    for (unsigned i=0; i<n; i++)
        numbers[ n ] = "kingkoy ";

    delete[] numbers;
    return 0;
}

See this site for more information on new and delete:
http://www.cplusplus.com/doc/tutorial/dynamic.html

See the C++ FAQ Lite for more on why to use new and delete instead of malloc and free:
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html

If you want "numbers" to be a dynamic array, you would be better off using one of the STL container types, like vector.

Hope this helps.

[EDIT] Oh yeah, watch your array subscripts.
[EDIT#2] Hmm, I just realized that the realloc thread was yours also. Give yourself a gold star for using google so well... ;-)
Last edited on
Topic archived. No new replies allowed.