473,888 Members | 2,194 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

16 bit pointer typecast on 16 bit system

Hi,

What does ANSI C say about casting an 8 bit pointer to a 16 bit one,
when the byte pointer is pointing to an odd address? I have detected a
problem in the Samsung CalmShine 16 compiler. This compiler I use for
the Samsung 16 bit Smartcard chips and I want to know if it is
compliant with the ANSI standard or if it violates it.

Have a look at this super simple example, where the value of b is
incorrect:

#include <stdio.h>

// Define an array in the EEPROM memory at address 0x081000
char data[8]={0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07} _at_
0x81000, eeprom;

int main ( void )
{
char a;
short b;
long c;
char* bpData;

// Set up the pointer to point to an odd address
bpData = &data[1];

// read a byte from an even address
a= *(bpData + 1);

// Read a word from an odd address. This causes problems. Instead of
// getting 0x0102 I get 0x001. What does ANSI C say about this?
b= *(short*)(bpDat a) ;

// just to check the value of the pointer, if the value of it is to
be stored in a variable
c= (long)bpData;

return 0x0 ;
}

Jul 3 '06
17 2735
Christian Wittrock wrote:
** SIGH ***

Your answer start out professionally but end as "I know all and you
know nothing"! Please do not post any replies if you do not have
respect for people.
At least Jack's message starts out professionally. Had you paid a little
attention to this group you would know that top posting is not
considered to be acceptable here. Your reply belongs after the parts of
the post you are responding to, not above it.

If you think Jack's response was impolite, I suggest that Usenet is not
the place for you. His reply was fairly mild.
I had assumed that people would disregard the EEPROM variable as the
question is not related to this.
If we don't know what it does, how can we know if it is relevant or not?
I did not explicitly write what
alignment the processor uses, as this is implicitly given in the
example. And again the alignment (odd or even) is not that relevant.
When doing type punning with pointers alignment is highly relevant.

<snip>
For someone who claims to be an expert and who talks down to others, I
would expect a bit more insigth than this. And it not good practise to
initialise variables within the declaration. Keep in mind that quite a
few embedded systems are put into a ROM chip, thereby creating the need
for a patch system. To initialize variables in the declaration will
make the compiler put in code before you can do a call to the patch
system.
Well, as Jack pointed out, you invoke undefined behaviour by casting a
pointer to another pointer type if it is not alligned correctly for the
type you are casting it to. Therefore anything can happen, including you
getting the result you are seeing or everyone taking an instant dislike
to you. Undefined behaviour means the behaviour is undefined.
I apologize for this angry reply, but I just got p***** off. You should
repect others more and answer any post in a professional way.
The correct approach is to not actually post if you feel a need to
apologise for the post in the post. Jack's reply gave you a reasonably
detailed description of why the code you wrote could fail, and correctly
suggested that you should have read the documentation about your
implementation so you know how it works.

<snip>
>Someone who programs embedded systems in C, using architectures
dissimilar to typical desk top processors, needs to know a fair bit
more the C standard, especially if you try to do things like pointer
punning.
The above is not insulting, it just points out that you need to know a
fair bit.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Jul 4 '06 #11
In article <11************ **********@m79g 2000cwm.googleg roups.com>,
Christian Wittrock <cu*@xponcard.d kwrote:
>** SIGH ***

Your answer start out professionally but end as "I know all and you
know nothing"! Please do not post any replies if you do not have
respect for people.
Chris, this is clc. You'll get used to it after a while. You might even
come to like it. After all, half a dozen "regulars", about as many
"trolls", and an uncountable number of newbies can't be wrong.

Useful clc-related links:

http://en.wikipedia.org/wiki/Clique
http://en.wikipedia.org/wiki/Aspergers
http://en.wikipedia.org/wiki/C_programming_language

Jul 4 '06 #12
On 4 Jul 2006 07:02:08 -0700, in comp.lang.c , "Christian Wittrock"
<cu*@xponcard.d kwrote:
>** SIGH ***

Your answer start out professionally but end as "I know all and you
know nothing"!
Actually, Jack's message did nothing of the sort. If you can't take
criticism of your code, then you need to get a different job.
>Please do not post any replies if you do not have
respect for people.
The R-word again. Its worth bearing in mind that you don't
automatically get respect, you have to earn it. By posting the reply
I'm commenting on, your account is going into debit.
>And excuse me for not knowing the standard by heart.
Of course.

Note however that you did get an answer to your question, and not one
which insulted you. Any percieved insult was entirely in your mind.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jul 4 '06 #13
Christian Wittrock wrote:
This compiler I use for
the Samsung 16 bit Smartcard chips and I want to know if it is
compliant with the ANSI standard or if it violates it.
I see you got a bunch of useless replies; here's my effort:
char data[8]={0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};

int main ( void )
{
char a;
short b;
long c;
char* bpData;

// Set up the pointer to point to an odd address
bpData = &data[1];

// read a byte from an even address
a= *(bpData + 1);
Same as:

a = bpData[1];

and correct.
// Read a word from an odd address. This causes problems. Instead of
// getting 0x0102 I get 0x001. What does ANSI C say about this?
b= *(short*)(bpDat a) ;
This causes undefined behaviour because bpData might not be
correctly aligned for short. For example, on your system, shorts
might only be readable from even-numbered addresses.

Even if the alignment was correct, it could be that the two bytes
at that address do not form a valid bit-pattern for a short.

This isn't possible on normal 8-bit-byte 2s-complement systems.
But you may find yourself porting to a strange system one day,
and IMHO there is really no good reason to write code that uses
this assumption, when you can write correct code instead.

Even on a 'normal' system, this code will be relying on endianness
to get the value you want. For example a big-endian system would
give 0x0102 and a small-endian would give 0x0201.

The correct way to write the code is to remember that C works
on values, not representations :

b = bpData[0] * 256U + bpData[1];

The 'U' is important as it forces the arithmetic to be unsigned.

In case you are worried about efficiency, try inspecting the
assembly output generated and you should find that that code
reduces to a very simple instruction.

If not, then IMHO it is still better to have slightly-slower but
robust code, than your original code.

In fact it's most likely that you want bpData itself to be a
pointer to unsigned char, and the char array to be unsigned. If
you aren't attaching any significance to the sign bit, or if you
are storing values greater than 127, or if you are planning to
use bitwise operations on the chars, then you should make the
chars unsigned. (Note that 0x80 is NOT a valid value for a signed
char).
// just to check the value of the pointer, if the value of it is to
be stored in a variable
c= (long)bpData;
This is also a non-portable operation, use it with care. Using
an unsigned long instead of a signed one tends to be more
reliable.

return 0x0 ;
"return 0" will do just as well :)

Jul 5 '06 #14
In article <nb************ *************** *****@4ax.com>,
Mark McIntyre <ma**********@s pamcop.netwrote :
....
>Note however that you did get an answer to your question, and not one
which insulted you. Any percieved insult was entirely in your mind.
Oh, the irony. How absolutely vapid.

You do realize that that bit of rhetoric ("it is all in your mind") has
been used repeatedly down through the ages to justify just about every
attrocity, do you not?

Jul 5 '06 #15
Christian Wittrock wrote:
>
I did not explicitly write what alignment the processor uses, as this
is implicitly given in the example.
Actually it isn't; going on the original message alone, your
program could have all sorts of possible alignment requirements.
And again the alignment (odd or even) is not that relevant.
The question was in relation to pointer casting behaviour when
accessing non-aligned memory locations.
You did not mention this in the original message. You only
mentioned a pointer cast when accessing an odd-addressed
byte of a global char array.
Shall a compiler automatically do the trick for you to be ANSI
compliant or not. And excuse me for not knowing the standard by heart.
ISO 9899:1999 6.3.2.3#7:

A pointer to an object or incomplete type may be converted
to a pointer to a different object or incomplete type. If the
resulting pointer is not correctly aligned for the pointed-to
type, the behavior is undefined.

In this quote, the first pointer is bpData and the "different object
type"
is short.
The reason why I posted my question was because I was faced with the
claim that the compiler (in question) is not ANSI C compliant.
Now you know that the compiler does not violate the Standard
in this respect.

First of all I always retrieve 16 bit values( or larger) on systems like this
one by getting a single byte at a time (the code has to be platform
independant).
How is one supposed to know this from reading your original
message?

When you post bad code on a help forum, you have to expect to
get responses saying what the correct code is and why. If you
aren't interested in the correct code, simply ignore these responses,
rather than insulting the people who have taken time out of their
day in an effort to help.
And it not good practise to initialise variables within the declaration.
Most programmers would disagree with this.
Keep in mind that quite a few embedded systems are put into a
ROM chip, thereby creating the need for a patch system. To initialize
variables in the declaration will make the compiler put in code before
you can do a call to the patch system.
That's a peculiarity of your system, and off-topic for this NG.

By which I mean, it's all well and good if you want to do that,
but you have to expect that people on here will write the best
code.
I apologize for this angry reply, but I just got p***** off. You should
repect others more and answer any post in a professional way.
You should show respect by not top-posting, and not
abusing people who are trying to help you. Also you should not
abuse people for not mysteriously knowing things that you did
not write in your original post (eg. the fact that it was an
unaligned access). You should realise that it is in fact possible
that there are people in the world who are equal or better
programmers than you, and if they are to be found anywhere,
then this NG is a more likely place than most.

Jul 5 '06 #16
Christian Wittrock wrote:
** SIGH ***

Your answer start out professionally but end as "I know all and you
know nothing"! Please do not post any replies if you do not have
respect for people.

I had assumed that people would disregard the EEPROM variable as the
question is not related to this. I did not explicitly write what
alignment the processor uses, as this is implicitly given in the
example. And again the alignment (odd or even) is not that relevant.
The question was in relation to pointer casting behaviour when
accessing non-aligned memory locations. Shall a compiler automatically
do the trick for you to be ANSI compliant or not. And excuse me for not
knowing the standard by heart.
As several people have told you by now. NO.
It is undefined behavior. ANSI C does not guarantee that that
cast will "work".
Some even provided a solution that doesn't invoke undefined behavior.
Please disregard the following sentences and only pay attention
to the above "It is undefined behavior" if this stirs up
your feelings:
Jack Klein told you this that it was undefined, and provided
several other helpful hints, and references to the relevarts
part of C according to your question. What did you fail to
understand about it ?

Jul 5 '06 #17
jjf

Christian Wittrock wrote:
** SIGH ***

Your answer start out professionally but end as "I know all and you
know nothing"! Please do not post any replies if you do not have
respect for people.

I had assumed that people would disregard the EEPROM variable as the
question is not related to this. I did not explicitly write what
alignment the processor uses, as this is implicitly given in the
example. And again the alignment (odd or even) is not that relevant.
The question was in relation to pointer casting behaviour when
accessing non-aligned memory locations. Shall a compiler automatically
do the trick for you to be ANSI compliant or not. And excuse me for not
knowing the standard by heart.

The reason why I posted my question was because I was faced with the
claim that the compiler (in question) is not ANSI C compliant. First of
all I always retrieve 16 bit values( or larger) on systems like this
one by getting a single byte at a time (the code has to be platform
independant). But again, that was not the question. The question is the
casting and not whether this a the correct way to code.

For someone who claims to be an expert and who talks down to others, I
would expect a bit more insigth than this. And it not good practise to
initialise variables within the declaration. Keep in mind that quite a
few embedded systems are put into a ROM chip, thereby creating the need
for a patch system. To initialize variables in the declaration will
make the compiler put in code before you can do a call to the patch
system.

I apologize for this angry reply, but I just got p***** off. You should
repect others more and answer any post in a professional way.
Did you consider reading the answer, or did you just decide to ** SIGH
** about it?

Jack's article gives complete and thorough answers to your questions.
As he (and several others) pointed out, the construct you are using is
invalid C and results in undefined behaviour. A conforming Standard C
compiler can do anything it chooses to when it sees this construct.
/Christian


Jack Klein skrev:
On 3 Jul 2006 03:24:56 -0700, "Christian Wittrock" <cu*@xponcard.d k>
wrote in comp.lang.c:
Hi,
>
What does ANSI C say about casting an 8 bit pointer to a 16 bit one,
The C standard says nothing at all about "8 bit pointers" and "16 bit
pointers". It talks about pointers to types, and those types can have
different sizes on different implementations . But we'll assume for
the moment that you know that characters have 8 bits and shorts 16
bits on your platform.
when the byte pointer is pointing to an odd address? I have detected a
problem in the Samsung CalmShine 16 compiler. This compiler I use for
the Samsung 16 bit Smartcard chips and I want to know if it is
compliant with the ANSI standard or if it violates it.
The C standard says that the behavior is undefined.
Have a look at this super simple example, where the value of b is
incorrect:
>
#include <stdio.h>
>
// Define an array in the EEPROM memory at address 0x081000
char data[8]={0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07} _at_
0x81000, eeprom;
Actually the minute you use the non-standard extension "_at_ 0x81000,
eprom", you have left the realm of the C standard behind. This means
nothing at all in standard C.

But assuming this results in a valid pointer to char...
int main ( void )
{
char a;
short b;
long c;
char* bpData;
>
// Set up the pointer to point to an odd address
bpData = &data[1];
If the non-standard definition does indeed create an array of chars
that your program has the right to access, this is a valid assignment
and places the address value 0x81000 in bpData.

But notice that you could have replaced the two lines with a simple
initialization in the definition of the pointer:

char *bpData = data + 1;
// read a byte from an even address
a= *(bpData + 1);
This is perfectly legal code, and assigned the contents of the char at
0x81002 to 'a'.
// Read a word from an odd address. This causes problems. Instead of
// getting 0x0102 I get 0x001. What does ANSI C say about this?
b= *(short*)(bpDat a) ;
The C standard says that if you use a pointer to something other than
a character type to access something, and the object does not have the
type of the pointer, the behavior is undefined.

C also says that when you convert pointer types, as your conversion
using a cast above, the result is undefined if the pointer is not
properly aligned for the new type.

I assume this is either a 16 or 32 bit processor, DSP, or
microcontroller . Some of these do have alignment requirements, and
accessing a 16-bit value on an odd address will violate these. The
results include a value that you consider "wrong", to generating a
hardware exception. An ARM, for example, will generate an address
abort.

Have you read the documentation on the processor, DSP, or
microcontroller that you are using? What are its address alignment
requirements?
// just to check the value of the pointer, if the value of it is to
be stored in a variable
c= (long)bpData;
>
return 0x0 ;
}
Someone who programs embedded systems in C, using architectures
dissimilar to typical desk top processors, needs to know a fair bit
more the C standard, especially if you try to do things like pointer
punning.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 5 '06 #18

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

Similar topics

1
2235
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen pertaining to casting class A to class B, the implementation of the
9
3540
by: Arun Prasath | last post by:
Hi all, I have the following question regd pointer typecasting. Is the following type of pointer typecasting valid? #define ALLOC(type,num) ((type *)malloc(sizeof(type)*num)) /*begin code*/
10
4144
by: Kieran Simkin | last post by:
Hi, I wonder if anyone can help me, I've been headscratching for a few hours over this. Basically, I've defined a struct called cache_object: struct cache_object { char hostname; char ipaddr; };
2
2183
by: dis | last post by:
The following code introduces a 'generic function pointer' p. When calling the pointed-to function via this p, one has to typecast p towards a pointer to the type of the pointed-to function. My question is how to do this if the pointed-to function is a K&R style declared function, like f. The best I could come up with is a typecast towards a pointer to a function with unspecified number and type of parameters (and appropriate return type),...
20
2132
by: j0mbolar | last post by:
I was reading page 720 of unix network programming, volume one, second edition. In this udp_write function he does the following: void udp_write(char *buf, <everything else omitted) struct udpiphdr *ui; struct ip *ip; ip = (struct ip *) buf;
19
8059
by: junky_fellow | last post by:
Can the size of pointer variables of different type may be different on a particular architecture. For eg. Can the sizeof (char *) be different from sizeof(int *) or sizeof (void *) ? What is the purpose of using a void pointer ? Instead of declaring a pointer variable "void *", can I declare it as "char *" and then later on typcast it to whatever type
22
28993
by: nick | last post by:
i do not know what is the use of (e.g. void *pt), when will use it. thanks!
22
2238
by: Brad | last post by:
Hi, Am trying to read one byte at location 0xFFF0 000E in an embedded system. I cast a pointer to int, then try to stuff the above address in, then reference whats at the location? wont compile, tried many different variations of this; any ideas appreciated.
41
4991
by: SRR | last post by:
Why is it discouraged to explicitly typecast the void pointer returned by malloc(); function? For example: { int *p; p = (int*)malloc(2*sizeof(int)); /*Explicit casting is done, therfore it is said to be a bad practice*/ /*Some codes*/ }
0
9957
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
10772
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
10878
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
10434
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
5810
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4635
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
2
4239
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3245
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.