Re: what am I missing?

new topic     » goto parent     » topic index » view thread      » older message » newer message
DerekParnell said...
jacques_desch said...

here C code from termbits.h

typedef unsigned char	cc_t; 
typedef unsigned int	speed_t; 
typedef unsigned int	tcflag_t; 
 
#define NCCS 19 
 
struct termios2 { 
	tcflag_t c_iflag;		/* input mode flags */ 
	tcflag_t c_oflag;		/* output mode flags */ 
	tcflag_t c_cflag;		/* control mode flags */ 
	tcflag_t c_lflag;		/* local mode flags */ 
	cc_t c_line;			/* line discipline */ 
	cc_t c_cc[NCCS];		/* control characters */ 
	speed_t c_ispeed;		/* input speed */ 
	speed_t c_ospeed;		/* output speed */ 
}; 

from this I compute 44 bytes for termios2 struct:

4*4 + 1 + 19 + 2*4 = 44

But if I allocate 44 bytes my program crash. I must allocate 45 bytes for it to works. Where is the missing byte?

Jacques

The C language leaves the packaging of data within a struct up to the compiler. Most compliers add padding bytes in order to ensure alignment of data on certain boundaries. In this case, it would appear that it tries to make sure that each new field begins on an even address, so I'm guessing there is a hidden padding byte between c_line and c_cc fields. However, that would also mean that you need to allocate 46 bytes because there should also be a padding byte after c_cc field.

Yes, it's very compiler dependent. I added the following to your struct definition:

#include <stdio.h> 
 
int main(){ 
	struct termios2 t; 
	printf("termios2: %d\n", sizeof( struct termios2 ) ); 
	printf("c_iflag:  %p\n", &t.c_iflag ); 
	printf("c_oflag:  %p\n", &t.c_oflag ); 
	printf("c_cflag:  %p\n", &t.c_cflag ); 
	printf("c_lflag:  %p\n", &t.c_lflag ); 
	printf("c_line:   %p\n", &t.c_line ); 
	printf("c_cc:     %p\n", &t.c_cc ); 
	printf("c_ispeed: %p\n", &t.c_ispeed ); 
	printf("c_ospeed: %p\n", &t.c_ospeed ); 
	return 0; 
} 
And with OpenWatcom v1.8, here's what I got:
  termios2: 44 
  c_iflag:  0006fe68 
  c_oflag:  0006fe6c 
  c_cflag:  0006fe70 
  c_lflag:  0006fe74 
  c_line:   0006fe78 
  c_cc:     0006fe79 
  c_ispeed: 0006fe8c 
  c_ospeed: 0006fe90 
So OW1.8 at least doesn't pad between byte sized members.

Matt

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu