473,947 Members | 5,488 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct member overlap?

Hi you,
I'm facing a strange problem, and I don't know what to do. Maybe
someone could help me understand this?

I'm storing IP and Netmask on the struct below.
1st I store IP an print it, its OK, like "127.0.0.1" .
Then I store Netmask and it somehow messes the IP's last octet, like
"127.0.0." ...
Check out line comments below, please...

Thanks

---------------begin code--------------------------------------------

#define inaddrr(x) (*(struct in_addr *) &ifr->x[sizeof sa.sin_port])
#define IFRSIZE ((int)(size * sizeof (struct ifreq)))

//This is the struct used to store IP and Netmask
struct ifinfo {
char * name;
char * ip;
char * netmask;
u32 ip32;
u32 netmask32;
};

....
....
....

//Stores IP on the struct
char *ip = inet_ntoa(inadd rr(ifr_addr.sa_ data));
if_info->ip = (char*) malloc(sizeof(* ip)+2);
strcpy( if_info->ip, ip );
if_info->ip32 = inaddrr(ifr_add r.sa_data).s_ad dr;

// *** Prints IP OK, like "127.0.0.1"
printf("\nIP=%s ", if_info->ip);

//Stores Netmask on the struct
if (0 == ioctl(sockfd, SIOCGIFNETMASK, ifr) &&
strcmp("255.255 .255.255", inet_ntoa(inadd rr(ifr_addr.sa_ data)))) {
char * netmask = inet_ntoa(inadd rr(ifr_addr.sa_ data));
if_info->netmask = (char*) malloc(sizeof(* netmask));
strcpy( if_info->netmask, netmask );
if_info->netmask32 = inaddrr(ifr_add r.sa_data).s_ad dr;
}

// *** Prints IP, without last octet, like "127.0.0."
printf("\nteste : %s=%s", ip, if_info->ip);

---------------end code--------------------------------------------

Nov 15 '05 #1
2 4632
hi******@gmail. com writes:
Hi you,
I'm facing a strange problem, and I don't know what to do. Maybe
someone could help me understand this?

I'm storing IP and Netmask on the struct below.
1st I store IP an print it, its OK, like "127.0.0.1" .
Then I store Netmask and it somehow messes the IP's last octet, like
"127.0.0." ...
Check out line comments below, please...

Thanks

---------------begin code--------------------------------------------

#define inaddrr(x) (*(struct in_addr *) &ifr->x[sizeof sa.sin_port])
#define IFRSIZE ((int)(size * sizeof (struct ifreq)))

//This is the struct used to store IP and Netmask
struct ifinfo {
char * name;
char * ip;
char * netmask;
u32 ip32;
u32 netmask32;
};

...
...
...

//Stores IP on the struct
char *ip = inet_ntoa(inadd rr(ifr_addr.sa_ data));
if_info->ip = (char*) malloc(sizeof(* ip)+2);
strcpy( if_info->ip, ip );
if_info->ip32 = inaddrr(ifr_add r.sa_data).s_ad dr;

// *** Prints IP OK, like "127.0.0.1"
printf("\nIP=%s ", if_info->ip);

//Stores Netmask on the struct
if (0 == ioctl(sockfd, SIOCGIFNETMASK, ifr) &&
strcmp("255.255 .255.255", inet_ntoa(inadd rr(ifr_addr.sa_ data)))) {
char * netmask = inet_ntoa(inadd rr(ifr_addr.sa_ data));
if_info->netmask = (char*) malloc(sizeof(* netmask));
strcpy( if_info->netmask, netmask );
if_info->netmask32 = inaddrr(ifr_add r.sa_data).s_ad dr;
}

// *** Prints IP, without last octet, like "127.0.0."
printf("\nteste : %s=%s", ip, if_info->ip);

---------------end code--------------------------------------------


Twice in the above code there are several statements that
look like they were intended to copy a string, but what they
do is unsafe (that is, wrong).

In particular, 'sizeof' is a compile-time operator, and does
not return the length of a string; rather it returns the
size of its operand. So

malloc(sizeof(* netmask))

allocates something that is the size of what 'netmask'
points to, which is to say 'sizeof(char)', which is to say 1
byte. That's not what you want.

The code can be simplified if it assumes the existence of a
function 'copy_string()' that returns a newly-allocated copy
of its string argument. See how the code is simplified:

//Stores IP in the struct
if_info->ip = copy_string( inet_ntoa(inadd rr(ifr_addr.sa_ data)) );
if_info->ip32 = inaddrr(ifr_add r.sa_data).s_ad dr;

//Stores Netmask in the struct
if(...condition ...){
if_info->netmask = copy_string( inet_ntoa(inadd rr(ifr_addr.sa_ data)) );
if_info->netmask32 = inaddrr(ifr_add r.sa_data).s_ad dr;
}

Now all we need to do is write copy_string():

char *
copy_string( const char *s ){
char *r = malloc( strlen(s) + 1 );

/* test malloc return value */
if( r == NULL ) exit(EXIT_FAILU RE); /* or whatever... */

return strcpy( r, s );
}

Notice that the function 'strlen()' is used to determine
the length of the string to copy. One extra character
is needed to store the 0 byte that's used to terminate
strings in C.
P.S. Please use spaces rather than tabs in news postings.
Nov 15 '05 #2
Groovy hepcat hi******@gmail. com was jivin' on 17 Sep 2005 10:50:22
-0700 in comp.lang.c.
struct member overlap?'s a cool scene! Dig it!
I'm storing IP and Netmask on the struct below.
1st I store IP an print it, its OK, like "127.0.0.1" .
Then I store Netmask and it somehow messes the IP's last octet, like
"127.0.0." ...

#define inaddrr(x) (*(struct in_addr *) &ifr->x[sizeof sa.sin_port])
#define IFRSIZE ((int)(size * sizeof (struct ifreq)))

//This is the struct used to store IP and Netmask
struct ifinfo {
char * name;
char * ip;
char * netmask;
u32 ip32;
u32 netmask32;
};

...
...
...

//Stores IP on the struct
char *ip = inet_ntoa(inadd rr(ifr_addr.sa_ data));
if_info->ip = (char*) malloc(sizeof(* ip)+2);


Don't cast the return from malloc(). The cast could hide a bug if
you fail to include stdlib.h. But that's probably unrelated to the
behaviour you describe.
You should have lurked in the newsgroup for some time before
posting. It is rude to post to a group without lurking first. I know
you didn't lurk because you are casting malloc()'s return. We are
forever telling people not to do that. You should also have read the
FAQ before posting.
ip is a pointer to char. sizeof *ip, therefore, is the size of a
char. That's one measly byte. What you're allocating here (if malloc()
succeeds, which you didn't check for - BAD!!!) is a grand total of
three bytes. How long is your string? Then how many bytes do you need
to allocate?
In future when you ask for help, please post a complete program, not
a mish-mosh of code snippets. If your program is longer than, say,
about 100 lines, cut it down to the smallest *complete* program that
still displays the problematic behaviour. By "complete" I mean
something you expect to compile and run. (And do try to compile and
run it to make sure it does still contain the error.)

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"?
Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5629
by: Angus Comber | last post by:
Hello I have received a lot of help on my little project here. Many thanks. I have a struct with a string and a long member. I have worked out how to qsort the struct on both members. I can do a bsearch on the long member (nKey) but I am struggling to do a search using the string member. The code I am running appears below. It doesn't crash or anything. It is just that when I do the last bsearch using "192.168.1.3" I SHOULD find...
2
1886
by: Michael B Allen | last post by:
My understanding is that struct members will remain in order such that the following can be used to support variable sized members: struct indexed_values { int *values; unsigned char bitset; }; struct meta_data { struct indexed_values foo;
60
3003
by: Mohd Hanafiah Abdullah | last post by:
Is the following code conformat to ANSI C? typedef struct { int a; int b; } doomdata; int main(void) { int x;
14
4727
by: indigodfw | last post by:
Greetings from India I would like to know the rationale on allowing structs to be assigned (using = operator) and not allowing equality operator ( == operator) on them. The compiler when it assigns using = is aware of holes etc and the same compiler then should be able to generate code to compare the individual struct fields.
3
2871
by: Michael B Allen | last post by:
Can offsetof be used to determine the offset of a member within an embedded struct member? For example, let 'struct foo' be a structure with an embedded structure 'struct bar' which has a member 'mem'. Can one do: offsetof(struct foo, bar.mem) Thanks, Mike
11
2065
by: Alfonso Morra | last post by:
Hi, I am at the end of my tether now - after spending several days trying to figure how to do this. I have finally written a simple "proof of concept" program to test serializing a structure containing pointers into a "flattened" bit stream. Here is my code (it dosen't work). I would be grateful for any feedback that helps fix this. My intention
8
1691
by: Mike | last post by:
The following struct, DataStruct, is only part of a larger one that contains additional fields and arrays. I need the explicit layout because this struct is really a union, where some of the missing fields and arrays overlap. What's shown here, though, is sufficient for explaining the error. 290 bytes of data come from a serial device and is to be placed in this struct. Hence, I want this struct to be 290 bytes in size, and, if I'm...
3
3907
by: Hallvard B Furuseth | last post by:
to find the required alignment of a struct, I've used #include <stddef.h> struct Align_helper { char dummy; struct S align; }; enum { S_alignment = offsetof(struct Align_helper, align) };
8
2190
by: anon.asdf | last post by:
Hi! OK, lets try "array-copy": { char arrayA; arrayA = (char){1, 2, 3}; } it does *not* work since we're trying to make a fixed array-pointer arrayA, point to another location/address (where there is an
0
10162
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11153
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11342
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9886
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8253
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7427
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4943
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3541
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.