Allocating memory and filling the structure elements of a structure - c

I have defined the structure in a separate header file and I have included that header file in my main file.
The header file consists of a structure like this:
typedef struct
{
char name[32];
unsigned int a;
unsigned int b;
NUMBER_ONE variable1;
NUMBER_TWO variable2;
}NUMBER_THREE,*PNUMBER_THREE;
typedef struct
{
unsigned int variable3;
char variable4[8];
}NUMBER_ONE,*PNUMBER_ONE;
typedef struct
{
unsigned int variable5;
char variable6[8];
}NUMBER_TWO,*PNUMBER_TWO;
Now in my main file I have to allocate memory for this structure and I need to fill this structure with some values, so anybody please tell me how to do this. I need to send this through socket client to the socket server.

If you have written it in that order you present it, then the code should not even compile since the first typedef has no clue on what NUMBER_ONE or NUMBER_TWO types are.
To allocate it should just be to define a variable of given type.
int main()
{
NUMBER_TWO number_two_var;
number_two_var.variable5 = 10;
}
I would also recommend using a postfix for each typdef, for example NUMBER_TWO_T.
Edit: Postfix being _T

In C a struct is initialized by an initializer
NUMBER_TWO a2 = { .variable5 = 7, .variable6 = { 'a', }, };
the form I am giving here are so-called designated initializers that came starting with C99. Oldish C had only the equivalent
NUMBER_TWO a2 = { 7, { 'a' } };
where you have to specify the values in declaration order.
For both forms, fields that are omitted from the initializer are initialized with 0.

Related

"Inheritance" in C's structs?

Here I'm a bit confused about this code:
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
struct test_struct {
uint8_t f;
uint8_t weird[];
};
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
printf("%u\n", test_in.weird[0]); // 0
test_in.tst.weird[0] = 1;
printf("%u\n", test_in.weird[0]); // 1
return 0;
}
I didn't know that it is possible to use struct's fields this way, so I have two questions:
How is it called in C?
And, of course, how does it work? (Why weird field was changed when I don't change it directly, I thought these are two different fields?)
Here I'm a bit confused about this code:
The short answer is: the code has undefined behavior.
How is it called in C? How does it work?
struct test_struct is defined with its last member as an array of unspecified length: uint8_t weird[]; This member is called a flexible array member, not to be confused with a variable length array.
6.7.2 Type specifiers
[...]
20     As a special case, the last member of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.
if you allocate such a structure from the heap with extra space for array elements, these elements can be accessed via the weird member up to the number of elements thus allocated.
The C Standard mandates that such a structure can only be defined as a member of another structure or union if it appears as the last member of said aggregate. In the posted code, the programmer violates this constraint, so accessing elements of test_in.tst.weird has undefined behavior, and so does accessing elements of test_in.weird.
The programmer also assumes that the test_in.tst.weird array and the test_in.weird array overlap exactly, which may be the case but is not guaranteed, nor supported: code relying on this type of aliasing has undefined behavior as well.
In your example, assuming the compiler accepts the empty initializer {} (part of the next C Standard and borrowed from C++), it seems to work as expected, but this is not guaranteed and alignment issues may cause it to fail as shown in the modified version below:
#include <stdint.h>
#include <stdio.h>
struct test_struct {
uint8_t f;
uint8_t weird[];
};
struct test_struct1 {
int x;
uint8_t f;
uint8_t weird[];
};
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
struct {
struct test_struct1 tst;
uint8_t weird[256];
} test_in1 = {};
printf("modifying test_in.weird[0]:\n");
printf("%u\n", test_in.weird[0]); // 0
test_in.tst.weird[0] = 1;
printf("%u\n", test_in.weird[0]); // 1
printf("modifying test_in1.weird[0]:\n");
printf("%u\n", test_in1.weird[0]); // 0
test_in1.tst.weird[0] = 1;
printf("%u\n", test_in1.weird[0]); // 0?
return 0;
}
Output:
chqrlie$ make 220930-flexible.run
clang -O3 -std=c11 -Weverything -o 220930-flexible 220930-flexible.c
220930-flexible.c:17:28: warning: field 'tst' with variable sized type 'struct test_struct' not at
the end of a struct or class is a GNU extension [-Wgnu-variable-sized-type-not-at-end]
struct test_struct tst;
^
220930-flexible.c:19:17: warning: use of GNU empty initializer extension [-Wgnu-empty-initializer]
} test_in = {};
^
220930-flexible.c:22:29: warning: field 'tst' with variable sized type 'struct test_struct1' not
at the end of a struct or class is a GNU extension [-Wgnu-variable-sized-type-not-at-end]
struct test_struct1 tst;
^
220930-flexible.c:24:18: warning: use of GNU empty initializer extension [-Wgnu-empty-initializer]
} test_in1 = {};
^
4 warnings generated.
modifying test_in.weird[0]:
0
1
modifying test_in1.weird[0]:
0
0
struct test_struct {
uint8_t f;
uint8_t weird[];
};
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
Effectively, before there were FAM's in the language, what you've declared is:
int main(void) {
struct {
struct { uint8_t f; } tst;
union {
uint8_t weird0[1]; // any non-zero size up to 256
uint8_t weird1[256];
} overlay;
} test_in = {};
On the contrary as described in the comments section above, a declaration like
int array[];
is not a Variable Length Array, it's either called Arrays of unknown size (cppreference) or Arrays of Length Zero (gcc).
An example of a VLA would be:
void foo(size_t n)
{
int array[n]; //n is not available at compile time
}
Based on the comment below (from the cppreference - see provided link):
Within a struct definition, an array of unknown size may appear as the last member (as long as there is at least one other named member), in which case it is a special case known as flexible array member. See struct (section Explanation) for details:
struct s { int n; double d[]; }; // s.d is a flexible array member
struct s *s1 = malloc(sizeof (struct s) + (sizeof (double) * 8)); // as if d was double d[8]
The provided code is just invalid.
You declared a structure with a flexible array member
struct test_struct {
uint8_t f;
uint8_t weird[];
};
From the C Standard (6.7.2.1 Structure and union specifiers)
18 As a special case, the last element of a structure with more than
one named member may have an incomplete array type; this is called a
flexible array member.
As it is seen from the quote such a member must be the last element of a structure. So the above structure declaration is correct.
However then in main you declared another unnamed structure
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
//...
that contains as member an element of the structure with the flexible array element that now is not the last element of the unnamed structure. So such a declaration is invalid.
Secondly, you are using empty braces to initialize an object of the unnamed structure. Opposite to C++ in C you may not use empty braces to initialize objects.

How to find all assignment expressions of a certain type

Say I have some struct definition like
struct sql_subtype {
sql_type *type;
unsigned int digits;
unsigned int scale;
}
This struct sql_subtype is used all over the place in my codebase which is huge. Objects of this type are often members of other objects. So simple string matching is not good enough to find the assignment locations. Is there some nice trick or open source static-analysis tool that can give me the locations in the code base where any object of this type is being set to some value? Find all locations similar to
struct sql_subtype type1 = type2;
or
c1->t = c2->t; // where the t's are of the type of interest.
etc.
The general problem: given the class of expressions that involve a certain operator that returns a certain type, how can I find all statements that contain expressions of this class?
Not a general solution, but there is a way to find the struct assignments with the C compiler alone. C allows you to declare members of struct as const, so you can add an extra member to the struct that is declared as const and only assignments will fail:
struct sql_subtype {
unsigned int digits;
unsigned int scale;
const unsigned int poison_pill;
};
void function_call(struct sql_subtype foo) {
struct sql_subtype initialized_from_copy = foo;
initialized_from_copy.digits = 42;
struct sql_subtype another = {0};
another = foo;
}
// if the const member is the last one even initializer lists will work!
struct sql_subtype initialized = {1, 2};
int main(void) {
function_call(initialized);
}
compile with GCC, and the only diagnostics you get are
constmemberhack.c: In function ‘function_call’:
constmemberhack.c:10:13: error: assignment of read-only variable ‘another’
another = foo;
^

How to use D structures from C code?

Could anyone explain me how to use D structures from C code? If I am trying to use it I receive such an error:
error: storage size of 'myStruct' isn't known
struct str_struct myStruct;
This is a structure:
extern(C) {
struct str_struct {
string str;
};
}
I use it in C like this : struct str_struct myStruct;
You have to duplicate the struct definition with all members in both languages (unless you want to refer to it only by pointer). C can't see a field list written in D.
D:
struct Foo {
int length;
int* data;
}
C:
typedef struct Foo {
int length;
int* data;
};
The tricky thing is to get long right. long in D is always 64 bits, so in C, that would be long long. Most other basic types translate pretty easily though: short=>short, int to int, char to char, pointers work the same way, etc.

How to copy the contents of an unpacked struct to a __packed__ struct?

I read about __packed__ from here and, I understood that when __packed__ is used in a struct or union, it means that the member variables are placed in such a way to minimize the memory required to store the struct or union.
Now, consider the structures in the following code. They contain same elements (same type, same variable names and placed in the same order). The difference is, one is __packed__ and the other is not.
#include <stdio.h>
int main(void)
{
typedef struct unpacked_struct {
char c;
int i;
float f;
double d;
}ups;
typedef struct __attribute__ ((__packed__)) packed_struct {
char c;
int i;
float f;
double d;
}ps;
printf("sizeof(my_unpacked_struct) : %d \n", sizeof(ups));
printf("sizeof(my_packed_struct) : %d \n", sizeof(ps));
ups ups1 = init_ups();
ps ps1;
return 0;
}
Is there a way where we can copy unpacked structure ups1 into packed structure ps1 without doing a member-variable-wise-copy? Is there something like memcpy() that is applicable here?
I'm afraid you've just gotta write it out. Nothing in standard C (or any standard I know of) will do this for you. Write it once and never think about it again.
ps ups_to_ps(ups ups) {
return (ps) {
.c = ups.c,
.i = ups.i,
.f = ups.f,
.d = ups.d,
};
}
Without detailed knowlegde of the differences of the memory layout of the two structures: No.

Using structure in C and C++

I am new to C and I want to know how to access elements inside a structure which is placed inside a structure.
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char src[4];
unsigned char dst[4];
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
How to access elements inside profile_t??
struct profile_t;
The above statement doesn't create an object of type profile_t. What you need to do is -
struct profile_t inObj ;
Then create object for profile_datagram_t. i.e.,
header outObj ; // header typedef for profile_datagram_t
Now you can access elements like -
outObj.inObj.type = 'a' ; // As an example
In C++, while creation of object for a structure, struct key word isn't necessary.
On your question edit and comment :
struct profile_t profiles[MAXPROFILES];
profiles is an array of objects of type profile_t. To access the individual object, just use the [] operator. i.e.,
header obj ;
obj.profiles[0].type = 'a' ; // Example
obj.profiles[i], where i can take values from 0 to MAXPROFILES - 1, gives the object at index i.
Not sure what happends in C, but in C++, rest of the stuff aside, the following declares two types.
struct profile_datagram_t
{
struct profile_t;
};
One type is named profile_datagram_t and the other is called profile_datagram_t::profile_t. The inner type declaration is just a forward declaration, so you'll need to define the type after.
struct profile_datagram_t::profile_t
{
// ...
};
Then, you can use the struct as follows:
int main ( int, char ** )
{
profile_datagram_t::profile_t profile;
}
Some compilers support a nonstandard extension to the C language (that I actually rather like, despite it being nonstandard) called anonymous structs (or unions). Code demonstration:
struct x {
int i;
};
struct y {
struct x;
};
int main(void)
{
struct y;
y.i = 1; // this accesses member i of the struct x nested in struct y
return 0;
}
In a nutshell, if you don't give the struct (or union) member a name, you can access its members directly from the containing struct (or union). This is useful in situations where you might have given it the name _, and had to do y._.i - the anonymous struct syntax is much simpler. However, it does mean that you have to remember the names of all members of both structs and ensure they never clash.
This is all, of course, a nonstandard extension, and should be used with caution. I believe it works on MSVC and can be enabled in GCC with a switch. Don't know about any other compilers. If you're worried about portability, give the member a proper name.
EDIT: According to the GCC reference (below) this behavior is being added to the upcoming C1X standard, so it won't be nonstandard for long. I doubt MSVC will support C1X since they refuse to support C99 as it is, but at least this feature is becoming part of the standard.
However, the behavior shown above is MSVC only. The C1X (and GCC without the -fms-extensions switch) syntax doesn't allow the unnamed struct member to have a name:
struct y {
struct {
int i;
};
};
int main(void) {
struct y;
y.i = 1; // this accesses member i of the struct x nested in struct y
return 0;
}
References for various compilers (they have different names but are the same concept):
GCC (unnamed fields): http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html'
MSVC (anonymous structs): http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
Basically you can use the following format:
variable = profile_t.element
profile_t.element = ?
EDIT: In your declaration of profile_datagram_t, the proper definition for struct profile_t should be:
struct profile_t someProfile;
Let's say you have:
header profileDiagram1;
struct profile_t profile1;
profileDiagram1.someProfile = profile1;
To access length, type or *data from profile_t:
profileDiagram1.someProfile.type;
profileDiagram1.someProfile.length;
...

Resources