Re: Why do not work?, is the same.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Am Dienstag, 13. September 2005 13:23 schrieb Fco. J:
> Block A: and B: are the same, but B: segfault.
>
> > #include <stdio.h>
> >
> > #define SIZE_MARCA (256 + 62)
> >
> > typedef struct Marca
> > {
> >   unsigned char str[SIZE_MARCA];
> >   unsigned int returned;
> > } marc;
> >
> > static struct Marca
> > marca (const unsigned char *page, const unsigned int id)
> > {
> >   struct Marca marca;
> >
> >   if (sprintf (marca.str, "%sTralara%u",page, (unsigned int) id) <= 0)
> >     {
> >       printf ("Error de salida de sprintf\n");
> >       marca.returned = 0;
> >     };
> >   marca.returned = 1;
> >   return marca;
> > }
> >
> > int
> > main ()
> > {
> > struct Marca tmp;
> > /*struct Marca (*puntero) (const unsigned char *page, const unsigned int
> > id);*/ /* A: */
> > tmp.str = marca("server_form.html", 1).str;
> > printf("TMP=%s\n",tmp.str);
> >
> > /* B: */
> >   printf ("1=%s \n", marca("server_form.html", 1).str);
> >   exit (0);
> > }
>
> Output:
> > ./tes2
> > TMP=server_form.htmlTralara1
> > Fallo de segmento
>

The statement tmp.str = marca(...).str  copies the CONTENTS of the string 
value, returned by the function which is ok, since when returning a variable  
of type struct Marca is shipped through the stack.

The second form in block B this variable will also ships through the stack.  
This time not the CONTENTS of the string is copied but the pointer to str 
field of the variable that has been created on the stack frame is given as an 
argument to printf.  The problem is, that while printf executes the stack 
frame contains the printf arguments.  The stack frame of the previously 
executed marca function has been deleted at this time.  But you still point 
to this stack frame by trading the str field pointer.

You should be carefull exchanging such objects through the stack.  It is much 
better to trade object references:

int marca( struct Marca* x, const char* y, int v) -> operate on x->str
and use the integer return value as an error indicator.  You are on the save 
side. 

int main (...) {
	int ret=0;
	struct Marca marca;

	if ( 0 == (ret=marca(&marca,"bla.html",1))  ) printf( "OK=%s\n", marca.str);
	return ret;
}

Attachment: pgpi55NiTUVRB.pgp
Description: PGP signature


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux