vendredi 13 mars 2015

Alternative to this code


I have a snippet of code like this:



struct a
{
a *b;
a()
{
b = new a;
}
};
int main()
{
a x;
}


It gives a Segmentation Fault as expected, because in the statement



b = new a;


It recursively defines the same structure over and over again, hence giving a segmentation fault.


gdb also tells me the same thing. Segmentation fault in malloc().



Starting program: /home/epsilon/m

Program received signal SIGSEGV, Segmentation fault.
0xb7d6f507 in _int_malloc (av=av@entry=0xb7ea4420 <main_arena>,
bytes=bytes@entry=4) at malloc.c:3302
3302 malloc.c: No such file or directory.


So, coming to the question,


Is there an alternative to this code?


That is, can this code be rewritten in such a way that it does not give a Segmentation Fault?


EDIT:


I am just asking this for learning purposes. This can be nearly emulated a linked list, but is there another way to do this?


P.S. Sorry for my incorrect language. I'm not good with words.




Aucun commentaire:

Enregistrer un commentaire