0
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct product{
        string productName;
        float price;
};

int main()
{
    struct product *article;
    int n=2; // n represent here the number of products
    article= (product*) malloc(n * sizeof(product));
    for(int i=0;i<n;i++)
    {
        cin >> article[i].productName; // <=> (article+i)->productName;
        cin >> article[i].price;
    }

    for(int i=0;i<n;i++)
    {
        cout << article[i].productName <<"\t" << article[i].price << "\n";
    }
    return 0;
}

My question is why this is wrong, because when I try to run this I get a segmentation fault. I used the GDB debugger to see which line is causing the problem, and this is the line that was causing this:

cin >> article[i].productName;

Why? This was bothering me for days...

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Yassine Bakkar
  • 107
  • 1
  • 13

4 Answers4

6

When you allocate memory with the new operator, it does two things:

  1. it allocates memory to hold an object;
  2. it calls a constructor to initialize the objects.

In your case (malloc), you do only the first part so your structure members are uninitialized.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

article[0] is not initialized (i.e. the constructor of struct product has not been called for article[0]). Therefore, article[0].productName has not been initialized either.

Use new product[n] instead of (product*) malloc(n * sizeof(product)) to initialize the array elements (and by transitivity the members of the elements).

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • 1
    @YassineBakkar use `std::vector article(n);` . Then the memory will be freed automatically. – M.M Mar 02 '15 at 00:05
1

Try using this:

#include <iostream>
#include <string>
using namespace std;
struct product{
    string productName;
    float price;
};

int main()
{
    int n = 2; // n represent here the number of products
    product *article = new product[n];
    for (int i = 0; i<n; i++)
    {
        cin >> article[i].productName; // <=> (article+i)->productName;
        cin >> article[i].price;
    }

    for (int i = 0; i<n; i++)
    {
        cout << article[i].productName << "\t" << article[i].price << "\n";
    }
    return 0;
}

article[0] was not initialized when you used cin. If you use new[] instead, it should work.

Kajgies
  • 31
  • 5
0

Instead of malloc-ing object, use new

product *article = new product[n];
nmserve
  • 11
  • 5