Operating System - Linux
1753821 Members
8757 Online
108805 Solutions
New Discussion юеВ

Re: Error in compiling C++

 
SOLVED
Go to solution
Henry Chua
Super Advisor

Error in compiling C++

I keep getting segmentation error when running this program... though I get no compiling error.Anyone care to drop a hint?
Codes:


#include
#include

using namespace std;

typedef struct
{
double a;
int b;
} AAA;

int main()
{
AAA *c, *v;

c->a = 1.1;
c->b = 2;
//*v = *c;
printf("TP\n");
//c->a = c->a*2;

printf("TP1\n");
cout << c->a << endl;
cout << c->b << endl;
printf("\n%d\n",&c->a);printf("%d\n",&v->a);
//cout << c << endl;
}
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Error in compiling C++

You have made a fundamental error. Note that this declaration allocates space for a pointer to a struct AAA but not the struct itself. Moreover, c points to an unitialized location so in some cases your code will actually work (in the sense that no segmentation violation will occur) but still be wrong.
BAD:
AAA *c;

Good:
AAA C,*c; /* declare both a struct and a pointer to struct*/
c = &C; /* Now set the pointer to the struct's address */
c->a = 1.1;
c->b = 2;

If it ain't broke, I can fix that.

Re: Error in compiling C++

You haven't allocated memory for the AAA registries.

Take into account that you have to allocate memory for them, a pointer is just a pointer.

Try this:

#include
#include

using namespace std;

typedef struct
{
double a;
int b;
} AAA;

int main()
{
AAA *c, *v;
c=new AAA;
v=new AAA;

c->a = 1.1;
c->b = 2;
//*v = *c;
printf("TP\n");
//c->a = c->a*2;

printf("TP1\n");
cout << c->a << endl;
cout << c->b << endl;
printf("\n%d\n",&c->a);printf("%d\n",&v->a);
//cout << c << endl;
}

Re: Error in compiling C++

Re-reading the code I realized that you only need an object, so just with the

c=new AAA;

would be enough, because after that you will point to the reserved area with the other v pointer.

It's really important working with C that you fully understand the difference between a pointer and the information it's pointing.

The pointer doesn't need to reserve memory, but you need to reserve memory for the data.

Once you have the data, of course you can point to that data so many pointers as you want without having to reserve more memory.
Henry Chua
Super Advisor

Re: Error in compiling C++

Thanks.. my qn is solved!
Dennis Handly
Acclaimed Contributor

Re: Error in compiling C++

Your compiler should have warned you that you had some uninitialized variables:
aCC6:
warning #2549-D: variable "c" is used before its value is set
c->a = 1.1;
^
warning #2549-D: variable "v" is used before its value is set
printf("%d\n",&v->a);
^
aCC3:
Warning 430: The variable 'v' is never initialized.
AAA *c, *v;
^
Warning 430: The variable 'c' is never initialized.
AAA *c, *v;
^