473,606 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using C99 "restrict" with newly allocated and initialized arrays/structures

Does the following code have defined behavior?

double *new_array(unsi gned n)
{
double *p = malloc(n * sizeof(double)) ;
unsigned i;
for (i = 0; i < n; i++) p[i] = 0.0;
return p;
}

int main(void)
{
double *restrict x = new_array(10), *restrict y = new_array(10);
x[0] = 1.0;
y[0] = 2.0;
return (int) x[0];
}

The use of "restrict" here is intended to inform the compiler that x
and y do not alias, so that the return value of main() is surely 1.
Without it, and if the compiler does not see the definition of
new_array() when compiling main() (e.g. because they are in different
translation units), it must assume that the two calls to new_array()
might return the same pointer.

However, according to 6.7.3.1p4 of the standard, the code seems to
have undefined behavior, because the lvalue "x[0]", whose address is
based on restricted pointer x, is used to access the object x[0] (and
it is modified), yet the initialization of that object to 0.0 in
new_array() uses the lvalue p[0], whose address p is not based on x
(indeed, x has not been initialized or used by that time). The
problem is that the no-non-based-alias restriction seems to apply to
the whole block containing the declaration of the restricted pointer
(in this case, the main() function), even before the pointer is
initialized.

Is my understanding correct? I suppose it is okay to do this:

int main(void)
{
double *x0 = new_array(10), *y0 = new_array(10);
{
double *restrict x = x0, *restrict y = y0;
x[0] = 1.0; y[0] = 2.0; return (int) x[0];
}
}

But it is clearly a bit too verbose.

Sep 23 '07 #1
6 2368
On Sep 23, 9:45 pm, rainy6...@gmail .com wrote:
Does the following code have defined behavior?

double *new_array(unsi gned n)
{
double *p = malloc(n * sizeof(double)) ;
unsigned i;
for (i = 0; i < n; i++) p[i] = 0.0;
return p;

}

int main(void)
{
double *restrict x = new_array(10), *restrict y = new_array(10);
x[0] = 1.0;
y[0] = 2.0;
return (int) x[0];

}

The use of "restrict" here is intended to inform the compiler that x
and y do not alias, so that the return value of main() is surely 1.
Without it, and if the compiler does not see the definition of
new_array() when compiling main() (e.g. because they are in different
translation units), it must assume that the two calls to new_array()
might return the same pointer.

However, according to 6.7.3.1p4 of the standard, the code seems to
have undefined behavior, because the lvalue "x[0]", whose address is
based on restricted pointer x, is used to access the object x[0] (and
it is modified), yet the initialization of that object to 0.0 in
new_array() uses the lvalue p[0], whose address p is not based on x
(indeed, x has not been initialized or used by that time). The
problem is that the no-non-based-alias restriction seems to apply to
the whole block containing the declaration of the restricted pointer
(in this case, the main() function), even before the pointer is
initialized.

Is my understanding correct? I suppose it is okay to do this:

int main(void)
{
double *x0 = new_array(10), *y0 = new_array(10);
{
double *restrict x = x0, *restrict y = y0;
x[0] = 1.0; y[0] = 2.0; return (int) x[0];
}

}

But it is clearly a bit too verbose.
IIRC, the restrict keyword is just a hint to the compiler for
optimization purposes. In other words, if a data element is read via
a restricted pointer, the compiler can assume that the read value
(possibly cached in a register) will not change unless modified via
the restricted pointer. In other words, if we need to use the value
again, we can use the cached value and not have to reread the element
from memory again, because we know (declared via the restrict pointer)
that it cannot change any other way.

So, I believe your original code is fine, since the function call is
part of the initialization, and the initialization is part of the
declaration. You do not access the data via any other means following
the declaration.

Regards,
B.

Sep 23 '07 #2
In article <11************ **********@y42g 2000hsy.googleg roups.com>
<ra*******@gmai l.comwrote:
>Does the following code have defined behavior?
I think it does:
>double *new_array(unsi gned n)
{
double *p = malloc(n * sizeof(double)) ;
unsigned i;
for (i = 0; i < n; i++) p[i] = 0.0;
return p;
}

int main(void)
{
double *restrict x = new_array(10), *restrict y = new_array(10);
x[0] = 1.0;
y[0] = 2.0;
return (int) x[0];
}

The use of "restrict" here is intended to inform the compiler that x
and y do not alias, so that the return value of main() is surely 1.
Without it, and if the compiler does not see the definition of
new_array() when compiling main() (e.g. because they are in different
translation units), it must assume that the two calls to new_array()
might return the same pointer.
Right.
>However, according to 6.7.3.1p4 of the standard, the code seems to
have undefined behavior, because the lvalue "x[0]", whose address is
based on restricted pointer x, is used to access the object x[0] (and
it is modified), yet the initialization of that object to 0.0 in
new_array() uses the lvalue p[0], whose address p is not based on x
(indeed, x has not been initialized or used by that time).
I think this is OK despite the wording you have quoted. I must,
however, admit that I do not fully understand some of the new bits
in C99, including the precise details of "restrict".

The *goal* of "restrict" is to allow the compiler to track aliases,
and the alias named p[i] in new_array() is completely gone before
the compiler can even begin to consider aliases named x[i]. Even
if the compiler chooses to expand new_array() in line and re-label
p as x, the restriction is "clearly visible" at that point, so this
*should* be allowed.

(This newsgroup -- comp.lang.c -- is probably not the best place
for a definitive answer as to whether the exact C99 wording means
what I think it does, or whether there are any corrections to it
since the version you are looking at, etc. The comp.std.c group
deals with picky wording details, corrections to the C standards,
future C standards, and so on. But here in comp.lang.c I will say
that I *think* your example code is OK as-is.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Sep 23 '07 #3
On Sep 23, 11:45 pm, rainy6...@gmail .com wrote:
Does the following code have defined behavior?

double *new_array(unsi gned n)
{
double *p = malloc(n * sizeof(double)) ;
No; you call malloc without a prototype visible.
x[0] = 1.0;
return (int) x[0];

The use of "restrict" here is intended to inform the compiler that x
and y do not alias, so that the return value of main() is surely 1.
It could be 0 due to floating point inaccuracies
(although not with IEEE754, if I understand that format correctly).

Sep 23 '07 #4
I thank you all for your helpful replies. I'll go to comp.std.c to
look for a more definitive answer.

On 9 24 , 4 09 , Chris Torek <nos...@torek.n etwrote:
The *goal* of "restrict" is to allow the compiler to track aliases,
and the alias named p[i] in new_array() is completely gone before
the compiler can even begin to consider aliases named x[i]. Even
if the compiler chooses to expand new_array() in line and re-label
p as x, the restriction is "clearly visible" at that point, so this
*should* be allowed.

(This newsgroup -- comp.lang.c -- is probably not the best place
for a definitive answer as to whether the exact C99 wording means
what I think it does, or whether there are any corrections to it
since the version you are looking at, etc. The comp.std.c group
deals with picky wording details, corrections to the C standards,
future C standards, and so on. But here in comp.lang.c I will say
that I *think* your example code is OK as-is.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.

Sep 24 '07 #5
ra*******@gmail .com wrote:
double *new_array(unsi gned n)
{
double *p = malloc(n * sizeof(double)) ;
unsigned i;
for (i = 0; i < n; i++) p[i] = 0.0;
return p;
}
int main(void)
{
double *restrict x = new_array(10), *restrict y = new_array(10);
x[0] = 1.0;
y[0] = 2.0;
return (int) x[0];
}
[ ... ] The
problem is that the no-non-based-alias restriction seems to apply to
the whole block containing the declaration of the restricted pointer
(in this case, the main() function), even before the pointer is
initialized.
I think you're right ! The aliasing restrictions begin a bit
too early. This could be a defect in the standard, or it could
be exactly what they meant.

I'll go look in comp.std.c too since you were redirected there,
but beware: there is already a threadlet pair on the subject,
but with trivial examples compared to yours. Make a good case.

BTW, this simpler example works too, doesn't it ?

static int a;
int *init(void) {a= 42; return &a;}
int main(void)
{
int * restrict p= init();
*p= 0;
return *p;
}
--
pa at panix dot com
Sep 24 '07 #6
On Sun, 23 Sep 2007 16:44:56 -0700, Old Wolf wrote:
> x[0] = 1.0;
return (int) x[0];
It could be 0 due to floating point inaccuracies
I don't think so. x[0] was assigned a constant, so it can be <1.0
only if double cannot contain 1 exactly. In the generic model in
the standard, this is possible: s is positive, e is 1, and all the
f_k's are zero except the first which is one.
--
Army1987 (Replace "NOSPAM" with "email")
A hamburger is better than nothing.
Nothing is better than eternal happiness.
Therefore, a hamburger is better than eternal happiness.

Sep 24 '07 #7

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

Similar topics

2
4802
by: Gerry | last post by:
I have a developer here with a website running with only "Windows Integrated Authentication" set on a Windows 2000 member server that uses GetObject to get a user's group membership in the domain. This is the code she's using: set adsUser = getobject("WinNT://" & strUsername) for each group in adsUser.groups GrpList = GrpList & lcase(trim(group.name)) & ";" next
0
1208
by: Perttu Pulkkinen | last post by:
Is there some way to restrict in mysql that certan field has only ONE ROW with CERTAIN VALUE X while other rows can have any values but not this one(so "unique" is not the answer..)? This can be of course done in application level, but it would just be nice to know. I would build my application so that only one user can be superadmin, while others are normal admins or something else. Of course this restriction would not be enough...
1
4565
by: Robert Fitzpatrick | last post by:
I am running PostgreSQL 7.4.5 and have a trigger on a table called tblriskassessors which inserts, updates or delete a corresponding record in tblinspectors by lookup of a contact id and license number match. The INSERT and DELETE work fine. The UPDATE works good unless I update the license number. The error, at the bottom of this message, suggests the primary key violation. But my UPDATE in no way alters the primary key, which is...
2
1253
by: Navneet Kumar | last post by:
Hi, My program is non-leaky, I've checked on that. More virtual memory is allocated to it by the system then is required by it. I'm filling a linked list which grows in size to around 1GB (at this point the VM is around 2GB) Pretty soon the 2GB limit is crossed and the program terminates. Comparatively VC6 version is allocated less VM then the VS2005 version. But still the 2GB limit is crossed. Is there any compiler switch etc that could...
2
2625
by: Frederick Gotham | last post by:
I'm going to be using an acronym a lot in this post: IINM = If I'm not mistaken Let's say we've got translation units which are going to be compiled to object files, and that these object files will be supplied to people to link with their own projects. Here's a sample function in one of the object files: void Func(int const *const p) {
5
1743
by: Francois Grieu | last post by:
Hello, I'm tring to implement a function that behaves like sprintf, but returns what it produce into newly mallocated memory block. I opened ISO/IEC 9899:1999, found int vsnprintf(char * restrict s, size_t n, const char * restrict format,
7
1970
by: jayakrishnanav | last post by:
Hi , Is it possible to restrict "pasting" any data in a text box,through keyboard(Ctrl-p) and through mouse??Can anybody help in dis WarmRegards jk
4
1459
by: Spiros Bousbouras | last post by:
Is there a way to mimick restricted pointers using array syntax ? So I'm looking for something to add to a statement such as "int arr" which will tell the compiler that I will only access the contents of the array through arr. If I was using pointers I would do for example int * restrict p = malloc(50 * sizeof(int)) Is there a way to do the same thing using arrays ?
13
1779
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
When I'm writing my own code, compiling it and testing it out as I go along, I usually compile as follows: gcc *.c -ansi -pedantic -Wall -o executable If I'm using 3rd-party libraries, I'll usually do the following: gcc *.c -Wall -o executable When I've already tested my code and I'm distributing it to other
0
8009
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
7939
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
8428
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
8078
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
8299
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
6753
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
5962
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
3919
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
1548
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.