Casting as Struct Pointer + Malloc
I have some ideas of what this would do, but I'd like a more professional and experienced explaination.
typedef struct{
char str[50];
unsigned short num;
}s;
s *name = (s *) malloc(sizeof(s));
The first part defines a struct. I have no problem with that
This will create a pointer to "s" struct. malloc()
returns a memory address that will be cast as a pointer to "s". However, sizeof(s)
I Believe I am having some issues understanding.
char str[50];
= 50 bytes.
unsigned short num;
= 2 bytes.
sizeof(s) returns 52 bytes?
malloc(sizeof(s))
allocates 52 bytes and returns the first address and casts it as a pointer to "s"?
One More Question! How can I perform error handling with malloc in-line?
Thanks to anyone that can help clarify this!
malloc
. malloc returns void* and in C, void* implicitly cast to whatever type you specify... sizeof(s)
depends on padding and also on the implementation (cos, sizeof(unsigned short)
will be different on different platforms...). In C, if you want to check for the error, you have to compare the return value of malloc
with NULL
.
if (name ==NULL) exit (1); //EXIT_FAILURE
The value of sizeof(s)
is implementation and ABI specific (it is at least 51 - and it could be 51 on hypothetical weird machines where sizeof(short)==1
and short
-s are aligned like char
is; I can't name any such machine). But on my Linux/Debian/Sid/x86-64 system (with x86-64 ABI) it is 52. And sizeof
is computed at compile time.
How can I perform error handling with malloc in-line?
The usual practice could be
s *name = malloc(sizeof(s));
if (!name) { perror("malloc of name"); exit(EXIT_FAILURE); };
链接地址: http://www.djcxy.com/p/28460.html
上一篇: 了解malloc
下一篇: 施放为结构指针+ Malloc