-3

I am trying to understand the concept of dynamic memory allocation. I have written some code that dynamically allocates an array of structs. The struct name is data and contains name and roll number. It asks user how many times you want to enter. After entering data it is supposed to search the data according to roll number. It crashes when searching for a particular roll number. Below is the code.

struct data
    {
        char name[50];
        int roll; float cgpa; char camp[3]; 

    };
    int main()
    {

        data *p;

        int i;
        cout << "how many times you want to enter data? "; cin >> i;
        p = new data[i];

        for (int k = 0; k < i; k++)

        {

            cout << "Enter your name:";
            cin >> p[k].name;

            cout << "Enter your roll number:";
            cin >> p[k].roll;

            cout << endl<<endl;
            p++;
        }
        int r;
        cout << "enter roll number to search for :"; cin >> r;
        for (int j = 0; i < i; j++){

        if (p[j].roll == r)
        {
            cout << "Roll number:" << p[j].roll << endl; cout << "Name:" << p[j].name << endl;

        }
        else{
            cout << "Not found!" << endl;
            break;
        }
    }
        delete []p;
        return 0;
    }
  • The simplest way to do things is probably to use `std::vector`. – Cheers and hth. - Alf May 24 '18 at 09:11
  • 4 times the same text ? – Tyker May 24 '18 at 09:11
  • I couldn't ask question because of too small explanation of code so that's why i have to copy paste it 4 times kindly ignore it. – Muzahir Hussnain May 24 '18 at 09:12
  • 1
    You should ask question properly instead of doing such a dirty hack. It hurts yourself. –  May 24 '18 at 09:14
  • @user463035818 Actually i don't find it to be a serious problem you should all be concern of code rather than of text. – Muzahir Hussnain May 24 '18 at 09:16
  • @Cheersandhth.-Alf i am not familiar with vectors – Muzahir Hussnain May 24 '18 at 09:17
  • 1
    Wrong, Both text and code are important. –  May 24 '18 at 09:17
  • @MuzahirHussnain: If you can, choose a book that teaches `std:.vector` up front. E.g. "Accelerated C++". See the C++ book list here on SO. Also, tip, you can use free tools such as AStyle to properly format your code before posting. Please do that in future. – Cheers and hth. - Alf May 24 '18 at 09:18
  • 1
    @NickyC Yeah it might be but in this case you can interpret what i am asking for can't you??Wouldn't it be great if you can deal with this problem rather than to taunt.Come up with some solution to this. – Muzahir Hussnain May 24 '18 at 09:20
  • 2
    @MuzahirHussnain code only question arent very usefull either. Anyhow, text has been fixed and I can remove my previous comment – 463035818_is_not_an_ai May 24 '18 at 09:22
  • 1
    just to let you know why i didnt retract my close vote: "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers." – 463035818_is_not_an_ai May 24 '18 at 09:25
  • @user463035818 Thank you for fixing it.I appreciate you for this. – Muzahir Hussnain May 24 '18 at 09:25
  • i didnt fix anything, you edited the text, no? – 463035818_is_not_an_ai May 24 '18 at 09:25
  • 2
    Yeah I might be able to interpret what you are asking. But wouldn't it be nice if you ask question properly rather than visually obscure fellows on the internet from helping you??? Show some decency. –  May 24 '18 at 09:25
  • 1
    @user463035818: The code only lacked include statements, which are customarily omitted in such examples. Not that I agree with the practice, but you're wrong to close-vote on those grounds. As with the silly downvoters here lacking fundamental competence about what they're voting about, please consider whether you really *know* what you're doing when you're about to vote. Like, "have I checked whether the code is complete or not, by trying to compile it"? – Cheers and hth. - Alf May 24 '18 at 09:26
  • @NickyC truly said... – Muzahir Hussnain May 24 '18 at 09:28
  • 1
    @MuzahirHussnain There are a lot of questions at SO, and people are using their own time to answer them. It's basic courtesy to make your question as clear as possible. Code formatting matters. Explanation matters. Related, when experienced programmers think code formatting is important for being able to work efficiently, I wonder why many novices think they are better and don't need well formatted code? – hyde May 24 '18 at 09:29
  • @hyde Okay, i got it what you are actually trying to convey i will take care of it in future and sorry for the inconvenience to all who are concerned about it.I apologize. – Muzahir Hussnain May 24 '18 at 09:35
  • @Cheersandhth.-Alf i was not refering to the code but rather to the "must include the desired behavior, a specific problem or error " part. However, I take your critic serious and I have to admit my vote really was not justified at all. – 463035818_is_not_an_ai May 24 '18 at 12:06
  • That's an ok-ish question. Maybe a specific error message would be useful. – Félix Adriyel Gagnon-Grenier May 24 '18 at 13:22

2 Answers2

2

In this code:

for (int k = 0; k < i; k++)   

{

    cout << "Enter your name:";
    cin >> p[k].name;

    cout << "Enter your roll number:";
    cin >> p[k].roll;

    cout << endl<<endl;
    p++;
}

You are incrementing the pointer to access and the index to access the pointer from so you going to far in memory.

Either iterate by index or by pointer/iterator.

Tyker
  • 2,971
  • 9
  • 21
-1

p is the array. It points to the start of the data reserved by new Data[i].

As soon as you increment it, it doesn't point to the start anymore.

Just drop the increment p++ statement and it'll work.

By the way there is no need to delete it at the end of main. It'll be freed anyway.

Thomas G.
  • 145
  • 7
  • 1
    _"By the way there is no need to delete it at the end of main. It'll be freed anyway."_ Really? – acraig5075 May 24 '18 at 09:20
  • @acraig5075: Yes. But depending on the context that might cause a report of leaking memory. – Cheers and hth. - Alf May 24 '18 at 09:21
  • 1
    if the data is allocated only once in the whole program and no allocation will ever be performed after the data should be freed you don't need to free BUT its a bad habit and there is no reason not to free – Tyker May 24 '18 at 09:22
  • 1
    I would argue not freeing memory and deferring deallocation to program termination are two different things, even if the generated machine code are the same. –  May 24 '18 at 09:34
  • @Cheersandhth.-Alf, @Tyker, @NickyC - See [why does the use of new cause memory leaks](https://stackoverflow.com/questions/8839943/why-does-the-use-of-new-cause-memory-leaks). Also, I recommend you read a beginners book on C++, such as [Stroustrup's Programming: Principles and Practice Using C++](https://www.amazon.com/Programming-Principles-Practice-Using-2nd/dp/0321992784/ref=dp_ob_title_bk?dpID=51j679vpDGL&preST=_SX218_BO1,204,203,200_QL40_&dpSrc=detail) which very clearly states on p. 600 that not using `delete` **causes a memory leak.** You usually should not rely on OS-freeing. –  May 24 '18 at 10:23
  • @Tellus: We were discussing the facts of the OP's code, not general recommendations. Also do note that memory leaks are not always negative: leaking memory can be an intentional choice for efficiency. It all depends. – Cheers and hth. - Alf May 24 '18 at 11:52
  • Wow! Back in 90s i developed an interpreter to parse a simple command script. It used only new() and not a single delete without leaking memory. I used a static memory buffer and overloaded the new operator. BTW That's not beginners level anyway. – Thomas G. May 25 '18 at 10:42