This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
RE: strcpy(stc->val,var) = Segmention Fault
- From: "Tony Wetmore" <tony dot wetmore at solipsys dot com>
- To: "'Rupert Wood'" <me at rupey dot net>, "'Uílton O. Dutra'" <uilton at schmitt dot com dot br>
- Cc: <gcc-help at gcc dot gnu dot org>
- Date: Mon, 21 Jul 2003 09:18:38 -0400
- Subject: RE: strcpy(stc->val,var) = Segmention Fault
Acutally, the problem is with the malloc for the char* storage into
stc->val. You need to add an extra byte to the malloc to accomodate
the null terminator character appended by strcpy.
This code:
stc->val=(char *) malloc(strlen(var));
needs to be replaced with:
stc->val=(char *) malloc(strlen(var) + 1);
It occurs in three places.
Hope this helps.
---
Tony Wetmore
Solipsys Corporation
mailto:tony.wetmore@solipsys.com
http://www.solipsys.com
-----Original Message-----
From: gcc-help-owner@gcc.gnu.org [mailto:gcc-help-owner@gcc.gnu.org] On
Behalf Of Rupert Wood
Sent: Sunday, July 20, 2003 8:14 AM
To: 'Uílton O. Dutra'
Cc: gcc-help@gcc.gnu.org
Subject: RE: strcpy(stc->val,var) = Segmention Fault
Uílton O. Dutra wrote:
> I create simple program to read configurations files.
> With Bcc32-Win98 my prog works fine, but on Gcc-Linux I got
> "Segmention Fault" in "strcpy(stc->val,var)".
This doesn't look linux-specific but lines 49-51 is where it first falls
over for me:
stc->next=(struct symtable *) malloc (sizeof (symtable));
stc=stc->next;
strcpy(stc->var," "); strcpy(stc->var," ");
You're allocating a new symtable and then attempting to write to use one
of its member pointers without assigning it first or allocating it
storage; you'd need a
stc->var = (char*)malloc(<something>);
before last strcpy, but I can't tell you what because it's not obvious
to me what you're doing there! The second strcpy, for example,
overwrites the first. (It's possible you meant to use one ->var and one
->val.)
It strikes me this structure is going to be a nightmare to free()
afterwards. Remember that malloc() doesn't zero the contents of the
memory it's allocated; at the very least you should cmalloc() your
symtables (or malloc then
memset(stc,0,sizeof(symtable))
them) so you can see which pointers you have used and should free() and
which you haven't (since they're NULL).
It's posslble I've overlooked some things here - I haven't given this a
lot of thought. Good luck making it work!
Rup.