473,761 Members | 2,440 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Another sizeof question

Please excuse me if this has already been covered.

Given

char x[42];

is

sizeof(x[999])

any kind of error? If so, since the expression is not evaluated, how
would such an error be detected? What if the declaration was

int n = 42;
char x[n];

?

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Sep 19 '07 #1
11 1592
ri*****@cogsci. ed.ac.uk (Richard Tobin) writes:
Please excuse me if this has already been covered.

Given

char x[42];

is

sizeof(x[999])

any kind of error?
[...]

I believe it's perfectly valid, and must yield 1.

x[999] is equivalent to *(x+999). The addition would invoke undefined
behavior, but only if it were evaluated.

I see no more reason for
sizeof(x[999])
to invoke UB than for
if (0) {
x[999];
}
to do so.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 19 '07 #2
On Sep 19, 3:09 am, Keith Thompson <ks...@mib.orgw rote:
I believe it's perfectly valid, and must yield 1.

x[999] is equivalent to *(x+999). The addition would invoke undefined
behavior, but only if it were evaluated.

I see no more reason for
sizeof(x[999])
to invoke UB than for
if (0) {
x[999];
}
to do so.
It really must be fine. A similar situation is this one, which can be
found gazillion times in everyone's code::

something* p;
p = malloc (sizeof (*p));

This is the recommended idiom to allocate memory, and the expression
*p on its own would invoke undefined behaviour just like x[999]. It's
fine because *p is not evaluated.
Sep 19 '07 #3
On Wed, 19 Sep 2007 00:16:49 +0000, Richard Tobin wrote:
Please excuse me if this has already been covered.

Given

char x[42];

is

sizeof(x[999])

any kind of error? If so, since the expression is not evaluated, how
would such an error be detected? What if the declaration was

int n = 42;
char x[n];
Even in this case, x's type is a VLA, but x[999]'s type is char,
so it is not evaluated by sizeof.

--
Army1987 (Replace "NOSPAM" with "email")
If you're sending e-mail from a Windows machine, turn off Microsoft's
stupid “Smart Quotes” feature. This is so you'll avoid sprinkling garbage
characters through your mail. -- Eric S. Raymond and Rick Moen

Sep 19 '07 #4
In article <11************ **********@50g2 000hsm.googlegr oups.com>,
christian.bau <ch***********@ cbau.wanadoo.co .ukwrote:
>It really must be fine. A similar situation is this one, which can be
found gazillion times in everyone's code::

something* p;
p = malloc (sizeof (*p));
Yes, that's a convincing argument.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Sep 19 '07 #5
In article <pa************ *************** *@NOSPAM.it>,
Army1987 <ar******@NOSPA M.itwrote:
> int n = 42;
char x[n];
>Even in this case, x's type is a VLA, but x[999]'s type is char,
so it is not evaluated by sizeof.
Oops, yes. Then what about

int n = 42;
char x[n][n];

sizeof(x[999]);

I can't see how it could cause a problem in practice, because what would
the compiler do with the result of computing x[999] anyway?

I haven't looked at how compilers handle this sort of thing, but I assume
they perform a kind of abstract interpretation in which expressions are
evaluated for their type rather than their value.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Sep 19 '07 #6
"Richard Tobin" <ri*****@cogsci .ed.ac.uka crit dans le message de news:
fc***********@p c-news.cogsci.ed. ac.uk...
In article <pa************ *************** *@NOSPAM.it>,
Army1987 <ar******@NOSPA M.itwrote:
>> int n = 42;
char x[n];
>>Even in this case, x's type is a VLA, but x[999]'s type is char,
so it is not evaluated by sizeof.

Oops, yes. Then what about

int n = 42;
char x[n][n];

sizeof(x[999]);

I can't see how it could cause a problem in practice, because what would
the compiler do with the result of computing x[999] anyway?

I haven't looked at how compilers handle this sort of thing, but I assume
they perform a kind of abstract interpretation in which expressions are
evaluated for their type rather than their value.
This is a good example of the problem with the wording of the Standard
regarding VLA-typed arguments to sizeof. There is no reason to evaluate
x[999] to determine its size. It looks like a defect in C99 IMHO.

--
Chqrlie.
Sep 19 '07 #7
Charlie Gordon wrote:
>
"Richard Tobin" <ri*****@cogsci .ed.ac.uka crit dans le message de news:
fc***********@p c-news.cogsci.ed. ac.uk...
[...]
Oops, yes. Then what about

int n = 42;
char x[n][n];

sizeof(x[999]);

I can't see how it could cause a problem in practice, because what would
the compiler do with the result of computing x[999] anyway?
[...]
This is a good example of the problem with the wording of the Standard
regarding VLA-typed arguments to sizeof. There is no reason to evaluate
x[999] to determine its size. It looks like a defect in C99 IMHO.
I assume you are referring to 6.5.3.4p2:

If the type of the operand is a variable length array type, the
operand is evaluated; otherwise, the operand is not evaluated and
the result is an integer constant.

Note that it says the operand is evaluated if it is a VLA, not if it
is a member of a VLA. In the above example, "sizeof(x[999])" would
not, IMO, evaluate the operand, because "x[999]" is not a VLA. Only
if you did "sizeof(x)" would it need to evaluate the operand "x".

Okay, hold on... (Isn't stream of consciousness writing fun?) I see
that x is a two-dimensional VLA in this new example. I guess that
that would mean that "x[999]" is a VLA.

Is it possible to have a VLA of different-sized VLAs? For example,
can the VLA "foo" have foo[1] point to a 3-element VLA while foo[2]
points to a 4-element VLA? If that can be done, then I can see why
it may be necessary to evaluate the operand of "sizeof(foo[x])".

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Sep 19 '07 #8
In article <46************ ***@spamcop.net >,
Kenneth Brody <ke******@spamc op.netwrote:
>Okay, hold on... (Isn't stream of consciousness writing fun?) I see
that x is a two-dimensional VLA in this new example. I guess that
that would mean that "x[999]" is a VLA.
Yes.
>Is it possible to have a VLA of different-sized VLAs?
No. There's no syntax for declaring such a thing, and it doesn't
make much sense implementationa lly: how would you represent it?
And if you come up with a way to represent it, it's unlikely to
be better than an array of pointers to different-sized arrays.
>For example,
can the VLA "foo" have foo[1] point to a 3-element VLA while foo[2]
points to a 4-element VLA?
Point to, but not be.

-- Richard

--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Sep 19 '07 #9
ri*****@cogsci. ed.ac.uk (Richard Tobin) writes:
In article <pa************ *************** *@NOSPAM.it>,
Army1987 <ar******@NOSPA M.itwrote:
>> int n = 42;
char x[n];
>>Even in this case, x's type is a VLA, but x[999]'s type is char,
so it is not evaluated by sizeof.

Oops, yes. Then what about

int n = 42;
char x[n][n];

sizeof(x[999]);

I can't see how it could cause a problem in practice, because what would
the compiler do with the result of computing x[999] anyway?

I haven't looked at how compilers handle this sort of thing, but I assume
they perform a kind of abstract interpretation in which expressions are
evaluated for their type rather than their value.
Since x[999] is a VLA, it's evaluated even when it's an argument to
sizeof, so this invokes undefined behavior.

In practice, since the evaluation isn't going to do anything, I would
expect an implementation to just compute the size and not try to read
the out-of-bounds array element.

My guess is that there's some case involving VLAs (or at least the
committee thought there was some case) where the evaluation is
actually necessary. The committee needed to define when arguments to
sizeof are evaluated and when they aren't; it was easier to say that
VLAs are evaluated than to define exactly when evaluation is
necessary.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 19 '07 #10

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

Similar topics

13
2551
by: Frank Wagner | last post by:
Hello NG! Though Im not new to programming at all, im new to C++. got the following question/problem with its behaviour: - read number with *arbitrary number of digits* from keyboard (done) - then calculate average value and variety of digits the second sould be no problem, too, i think.
19
9235
by: Martin Pohlack | last post by:
Hi, I have a funtion which shall compute the amount for a later malloc. In this function I need the sizes of some struct members without having an instance or pointer of the struct. As "sizeof(int)" is legal I assumed "sizeof(struct x.y)" to be legal too. But is is not: #include <dirent.h>
26
1835
by: Materialised | last post by:
Hi everyone, I seen the post by Rob Morris, and thought that I would double check that I was using pointers in the correct way. So I written the following string functions to test. I know soem can be iumplimented using the standard libary, but I just wanted to test writing my own functions. They work ok, but I would like some feed back on any issues you can see with them etc #include <stdio.h> #include <stdlib.h>
42
2409
by: Christopher C. Stacy | last post by:
Some people say sizeof(type) and other say sizeof(variable). Why?
5
5313
by: Yourko | last post by:
Hi there! I`me currently trying to write some simple programs in C. For one such program i created globals.h file. In that file i defined a structure of type _client, and a pointer of that type: struct _client{ int fd; // file descriptor struct sockaddr_in sock_name; } * client; Later in that program i do: client = (struct _client *) malloc(sizeof(struct _client));
12
3996
by: Yusuf | last post by:
I'm sorry for the second post in as many hours, and both about structs. The code below compiles. The variables test1 and test2 are structures of datatype teststruct1 and teststruct2. The size of testintArray is explictly set to 2 and 3 in teststruct1 and teststruct2. I want to define a generic structure so that testintArray points to an array of ints. The generic structure I have written is teststruct3. What I can't seem to figure out...
19
1511
by: lawtrevor | last post by:
I have a question regarding the use of free() based on some code I need to decipher: { struct A {<A fields>}; struct B {<A fields+ <Bfields>}; typedef struct A Aobj; typedef struct B Bobj;
14
2795
by: ManicQin | last post by:
Hi all. I'm trying to get the size of a variable in a struct by his relative postion i.e. /// #define offsetof(s,m) (size_t)&(((s *)0)->m) struct ThePimp{ char rings; char blings;
11
3953
by: michelqa | last post by:
Hello, I can retrieve column text from a ListView in another process but I cant figure out how to access to structure elements (LVCOLUMN) <code> //Handle variable is a valid ListView handle LV_COLUMN ListViewItem = new LV_COLUMN(); IntPtr ListViewItemPointer = IntPtr.Zero;
0
9522
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9336
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10111
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9765
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
8770
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 projectplanning, coding, testing, and deploymentwithout 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...
0
6603
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();...
0
5215
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...
1
3866
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
2738
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.