Reputation: 508
I am trying to execute following code which is giving me segmentation fault. What error I am doing or am I missing any part ? can this code be implemented in some other way?
Code:
#include <iostream>
#include "string.h"
using namespace std;
struct A {
char* a;
};
int main()
{
struct A *x;
x->a = "soumya";
char* str = "soumya";
cout<<str<<endl<<(char*)x->a<<endl;
// if(strcmp(x->a,str)!=0)
// {
// cout<<"not same"<<endl;
// }
return 0;
}
Upvotes: 1
Views: 119
Reputation: 717
You are not initializing the x
pointer to struct A
so initially it points to some undefined area in memory which is not allocated.
So by doing x->a = "soumya";
you are trying to write this space which causes segmentation fault.
You can change
struct A *x;
to
struct A *x = malloc(sizeof(struct A));
// Don't forget to free this memory if your program is going to run for some time
or to
struct A x;
And replace every x->a
with x.a
in this case memory is allocated in stack so it will automatically be freed at the end of the method.
Upvotes: 4
Reputation: 106
Here is a corrected version :
Use of const char *
because you assign constant string
Use of struct A x;
to have the struct
allocated and not only a pointer to a non allocated memory.
#include <iostream>
#include "string.h"
using namespace std;
struct A {
const char* a;
};
int main()
{
struct A x;
x.a = "soumya";
const char* str = "soumya";
cout<<str<<endl<<x.a<<endl;
return 0;
}
Upvotes: 1
Reputation: 7017
There are several issues we need to cover.
1) do not use raw pointers in C++ anymore, in general.
2) you do not actually allocate any memory for *x
. This can be achieved by doing:
struct A *x = new A;
Remember to call delete x
, to deallocate the memory when appropriate.
The third problem is that you do not allocate memory for the content of x->a
. The best solution is to use std::string
instead of a char pointer.
Then you are allowed to do x->a = "soumya";
.
You struct should then be
struct A {
std::string a;
};
Upvotes: 2