jeudi 29 septembre 2016

Why am i getting a runtime error when using malloc()

I some times get a runtime error and sometimes my program triggers a break point. The following programs takes value form user and creates a dynamic array of that size. If the user keeps on entering the add data option the size of array is doubled and user is allowed to add further data. Now if i input the size of dynamic array as 1 then after almost 11 entries i get a runtime error or sometimes the program also triggers a break point. What is the reason for that

#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
    int size = 0;
    cout << "Please Input The Size of Your List: ";
    cin >> size;
    int curremt = 0;
    int in_check = 0;
    int del_check = 0;
    int * list;
    list = (int*)malloc(size);
    char choice = ' ';
    while (choice != 'E'|| choice != 'e') {
        system("cls");
        cout << "Press 1 to Add data"<<endl;
        //cout << "Press 2 to Delete data" << endl;
        cout << "Press 3 to  View data" << endl;
        cout << "Press E to Exit" << endl;
        cout << "Please Input Choice: ";
        cin >> choice;
        if (choice=='1') {
            in_check++;
            if (!(in_check>size))
            {
                cout << "Please Input Data: ";
                cin >> list[curremt];
                curremt++;
            }
            else {
                int * temp = new int[size];
                for (int i = 0; i < size; i++)
                {
                    temp[i] = list[i];
                }
                list = (int*)realloc(list, (size * 2));
                for (int i = 0; i < size; i++)
                {
                    list[i] = temp[i];
                }
                delete[] temp;
                size = size * 2;
                cout << "Please Input Data: ";
                cin >> list[curremt];
                curremt++;
                in_check = ((size/2)+1);
            }
        }
        else if (choice == '3') {
            for (int i = 0; i < curremt; i++)
            {
                cout << "Data At Position " << i << ":" << list[i]<<endl;
            }
            Sleep(500*size);
        }
        else if (choice == '2') {

        }
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire