[oclug] time for my weekly dumb question -> C and memory

Bart Trojanowski bart at nexus.carleton.ca
Sun Apr 1 22:37:55 EDT 2001


Ah, just read David's reply... for network packets you cannot do this.
Read his mail first. ;)

On Sun, 1 Apr 2001, Bart Trojanowski wrote:

>
> Hey Greg,
>
>   you may do something like this...
>
> typedef struct {
>   unsigned short url_length;
>   char *url;
>   unsigned short scope_length;
>   char *list;
>   char data[0];
> } service_advert;
>
> service_advert*
> service_advert_new( unsigned short url_length, unsigned short scope_length )
> {
>   service_advert *sa;
>   unsigned total_len = sizeof(service_advert) + url_length + scope_length;
>
>   sa = (service_advert*) malloc (total_len);
>   if( !sa ) return NULL;
>
>   sa->url_length = url_length;
>   sa->url = sa->data;
>
>   sa->scope_length = scope_length;
>   sa->list = sa->data + url_length;
>
>   return sa;
> }
>
> To be consistant you should have a service_advert_delete(service_advert*)
> as well.
>
> B.
>
>
> On Sun, 1 Apr 2001, Greg Sarsons wrote:
>
> > Okay just noticed that.  But what if you have fields that you don't know the
> > size of until you are building the messages?  How does one get around that
> > problem?
> >
> > in my case my outgoing url has a length  and so does the scope_list.  Can
> > either of these be used to solve the problem?
> >
> > I wish the fields had a set size but it can range from 0 to the point where
> > I've got to use TCP instead of UDP to send the message.
> >
> > Greg
> >
> > On Sunday 01 April 2001 21:11, you wrote:
> > > On Sun, 1 Apr 2001, Greg Sarsons wrote:
> > > > typedef struct{
> > > > 	unsigned short url_lenght;
> > > > 	char url[0];
> > > > 	unsigned short lengthOfScopeList;
> > > > 	char scope_list[0];
> > > > } ServiceAdvert;
> > >
> > > That is not a valid C structure, and I'm amazed anything will compile
> > > it.  Zero-length arrays are meaningless, and are allowed at the end of a
> > > structure (only) as a hack by some compilers.
> > >
> > > > However, as soon as I do a strcpy into the other zero length string,
> > > > scope_list, the url is messed up.
> > >
> > > Look at the memory layout of the structure.  Anything you write into url
> > > will overwrite lengthOfScopeList and probably scope_list.
> > >
> > > --
> > > David.
> > >
> > >
> > > _______________________________________________
> > > oclug mailing list
> > > oclug at lists.oclug.on.ca
> > > http://www.oclug.on.ca/mailman/listinfo/oclug
> > _______________________________________________
> > oclug mailing list
> > oclug at lists.oclug.on.ca
> > http://www.oclug.on.ca/mailman/listinfo/oclug
> >
>
>

-- 
	WebSig: http://www.jukie.net/~bart/sig/





More information about the OCLUG mailing list