473,804 Members | 2,246 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Index out of bounds question

Say I have the following:

int main(void) {
char* p, q;
p = (char*) malloc(sizeof(c har)*10);
q = (p + 100) - 99; /* legal? */
free(q - 1); /* legal? */
....
return 0;
}

Will this program always produce UB, always work, or is it compiler
dependent?
Nov 14 '05 #1
26 2031
Method Man wrote:
Say I have the following:
#include <stdlib.h>
int main(int argc, char* argv[]) {
char* p = (char*)malloc(s izeof(char)*10) ;
char* q = (p + 100) - 99; // illegal!
free(q - 1); // illegal!
// ....
return 0;
} Will this program always produce UB?
This is an improper question.
Undefined Behavior (UB) is undefined.
There is no specific behavior to "produce".
Always work?
It works everywhere.
Or is it compiler dependent?


There are no ANSI/ISO C99 compliant compilers
that will not accept this code
and generate the expected output.
Nov 14 '05 #2
"Method Man" <a@b.c> writes:
Say I have the following:

int main(void) {
char* p, q;
This is deceptive syntax. It *looks* like it's meant to declare
two pointers, but it *actually* declares a pointer and an
integer.
p = (char*) malloc(sizeof(c har)*10);
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.

* If you cast to the wrong type by accident, odd failures can
result.

Some others do disagree, such as P.J. Plauger (see article
<9s************ *****@nwrddc01. gnilink.net>).

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (128 * sizeof (int)); /* Don't do this! */

Instead, write it this way:

int *x = malloc (128 * sizeof *x);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.

Finally, sizeof(char) is always 1.
q = (p + 100) - 99; /* legal? */
Constraint violation that requires a diagnostic. See C99
6.5.16.1 "Simple assignment". Also, the pointer arithmetic
yields undefined behavior, because you're going beyond
one-past-the-end in an array.
free(q - 1); /* legal? */
Also a constraint violation. See C99 6.5.2.2 "Function calls"
para 2.
....
return 0;
}

Will this program always produce UB, always work, or is it compiler
dependent?


It won't compile without diagnostics. It also produces undefined
behavior.
--
Ben Pfaff
email: bl*@cs.stanford .edu
web: http://benpfaff.org
Nov 14 '05 #3
In article <sp************ *****@read1.cgo cable.net>, Method Man <a@b.c> wrote:
Say I have the following:

int main(void) {
char* p, q;
p = (char*) malloc(sizeof(c har)*10);
Don't Do That.
This line is broken, since you forgot to #include <stdlib.h>; the compiler
incorrectly assumes (as required by the language definition) that malloc
returns int, and your cast prevents it from complaining about attempting
an invalid conversion (from int to pointer).
Preferred form:
p = malloc(10 * sizeof *p);
Since sizeof(char) is required to be 1, in this case you can even do:
p = malloc(10);
q = (p + 100) - 99; /* legal? */
No, but unlikely to cause problems on systems with a flat memory space
and general-purpose registers used for both pointer and integer operations
(that is, pretty much any system you're ever likely to use).
free(q - 1); /* legal? */
If q is a valid pointer to 1 past the pointer you got from malloc (which,
as noted above, is the only result you're likely to see from the line
above), this is legal and will do exactly what you appear to expect.
....
Badly formed code.
return 0;
}
Will this program always produce UB, always work, or is it compiler
dependent?


Always produce UB, and almost always (but compiler and, more likely,
hardware dependent) do the "exactly what you expect" that's the worst
possible kind of UB (except perhaps the "exactly what you expect, until
somebody important is watching" kind).

A system that checks every pointer value generated (such systems are
well within the bounds of the requirements on implementations , though
I'm not sure if any actually exist) can trap after evaluating `(p+100)'
(the left operand of the '-' operator in the line of code you're asking
about), since this generates a pointer that's 90 bytes past the end
of the chunk of memory allocated by malloc. Most systems only check
pointers (if at all) when you dereference them and not when you create
them, and since you never dereference this particular invalid pointer,
this check won't catch it.
dave

--
Dave Vandervies dj******@csclub .uwaterloo.ca
Since you're a hobbyist, I'm sure you'll want to write the code more
correctly than a mere professional might do.
--Richard Heathfield in comp.lang.c
Nov 14 '05 #4
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > writes:
Method Man wrote:
Say I have the following:


#include <stdlib.h>
int main(int argc, char* argv[]) {
char* p = (char*)malloc(s izeof(char)*10) ;
char* q = (p + 100) - 99; // illegal!
free(q - 1); // illegal!
// ....
return 0;
}

Will this program always produce UB?


This is an improper question.
Undefined Behavior (UB) is undefined.
There is no specific behavior to "produce".
Always work?


It works everywhere.
Or is it compiler dependent?


There are no ANSI/ISO C99 compliant compilers
that will not accept this code
and generate the expected output.


Tisdale has lied to us yet again. The code quoted above is not what
Method Man wrote. It's obvious that Tisdale isn't going to respond to
complaints, so I'll just post this as a warning to others.

The actual code was:

] int main(void) {
] char* p, q;
] p = (char*) malloc(sizeof(c har)*10);
] q = (p + 100) - 99; /* legal? */
] free(q - 1); /* legal? */
] ....
] return 0;
] }

Method Man's code had serious error: "char *p, q;" declares p as a
pointer to char, and q as a char. Tisdale, for some unfathomable
reason, decided to quietly pretend the error didn't exist rather than
tell Method Man about it.

(Note to Mabden: Based on your past behavior I expect you'll jump in
and flame me for calling Tisdale on his lie. I know your opinion on
the matter and I'm really not interested in hearing about it again.)

Assuming the declaration is corrected to

char *p, *q;

the evaluation of p + 100 invokes undefined behavior, because it
yields a value outside the bounds of the memory allocated by malloc().
Once undefined behavior is invoked, all bets are off.

If you change the statement
q = (p + 100) - 99;
to
q = (p + 10) - 9;
there's no problem; p+10 points just past the last element of the
allocated memory (which is ok as long as you don't dereference it),
and q then points to p[1]. q - 1 is then equal to p, and passing that
value to free() is valid.

Will it "work"? Quite possibly. The possible consequences of
undefined behavior always include behaving just as you expect
(assuming you have any expectation). It may or may not be the case
that the code "works" in all existing implementations , but a
bounds-checking implementation with fat pointers could easily trap.
The only sensible thing to do is avoid the undefined behavior in the
first place.

--
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.
Nov 14 '05 #5
E. Robert Tisdale wrote:
Method Man wrote:
Say I have the following:


#include <stdlib.h>

int main(int argc, char* argv[]) {
char* p = (char*)malloc(s izeof(char)*10) ;
char* q = (p + 100) - 99; // illegal!


Excuse me, Sir, but you are mis-quoting the Man.

Don't do that.

--
Chris "electric hedgehog" Dollin
Nov 14 '05 #6
Chris Dollin <ke**@hpl.hp.co m> scribbled the following:
E. Robert Tisdale wrote:
Method Man wrote:
Say I have the following:
#include <stdlib.h>

int main(int argc, char* argv[]) {
char* p = (char*)malloc(s izeof(char)*10) ;
char* q = (p + 100) - 99; // illegal!

Excuse me, Sir, but you are mis-quoting the Man. Don't do that.


Telling Tisdale not to mis-quote people is like telling P.J.Plauger not
to advertise his compiler, Dan Pop not to tell people to engage their
brains, or me not to insult people. I.e. like talking to a brick wall.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"This is a personnel commuter."
- Train driver in Scientific American
Nov 14 '05 #7
In <ck**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
Telling Tisdale not to mis-quote people is like telling P.J.Plauger not
to advertise his compiler,


Huh?!?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #8
In article <ck**********@s unnews.cern.ch> , Dan Pop <Da*****@cern.c h> wrote:
In <ck**********@o ravannahka.hels inki.fi> Joona I Palaste
<pa*****@cc.he lsinki.fi> writes:
Telling Tisdale not to mis-quote people is like telling P.J.Plauger not
to advertise his compiler,


Huh?!?


Since, as far as I know, PJP doesn't have a compiler to advertise,
telling him not to advertise it wouldn't do much good, would it?

(Though I think Joona really meant to say Jacob Navia here.)
dave

--
Dave Vandervies dj******@csclub .uwaterloo.ca
I should also have said that it's perfectly possible to do this in
multiple dimensions. Just hurts a bit to think about...
--Peter Boyle in comp.arch
Nov 14 '05 #9
Dave Vandervies <dj******@csclu b.uwaterloo.ca> scribbled the following:
In article <ck**********@s unnews.cern.ch> , Dan Pop <Da*****@cern.c h> wrote:
In <ck**********@o ravannahka.hels inki.fi> Joona I Palaste
<pa*****@cc.h elsinki.fi> writes:
Telling Tisdale not to mis-quote people is like telling P.J.Plauger not
to advertise his compiler,
Huh?!?

Since, as far as I know, PJP doesn't have a compiler to advertise,
telling him not to advertise it wouldn't do much good, would it? (Though I think Joona really meant to say Jacob Navia here.)


Yes, I meant Jacob Navia. Sorry.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"C++ looks like line noise."
- Fred L. Baube III
Nov 14 '05 #10

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

Similar topics

0
2769
by: Eugene | last post by:
Hello all, I've been trying to figure this out for a few days now, and still have no clue what's going on... I have a few related tables in MS Access (Clients, Cars, Sales), and a datagrid, binded to dataview. Here's a catch - whenever I select a client, and then find a car which belongs to this client, and click on empty space in datagrid (that is in gray area below rows) - I get "Index was outside the bounds of the array" error......
0
2130
by: scotthutchinson | last post by:
I have a .NET Remoting object hosted in IIS6 on Windows Server 2003 (happens before and after installing SP1) at an endpoint (ASP.NET application virtual folder) named "CompanyXYZReporting". The remoted object is called several times every day and works perfectly except every 2-3 weeks when we call the remoted object, the response returns the error shown below. Does anyone have any clues how to resolve this problem? Server Error in...
2
3807
by: Denis C | last post by:
Hi there, I'm trying to convert part of a byte array into a series of fixed length strings but half way through the for loop I get an error that I'm accessing outside the buffer bounds. The error: An unhandled exception of
4
3613
by: Antoine | last post by:
Herfried and Cor:- I used tracing and actually tracked down the code that was causing the problem most likely. I wonder if you wanted to comment on it. Also I wonder if there is a better way of testing if there is data than testing the length of the xml string I used as stringreader to create the dataset, but thats a side issue. I think I tried isdbnull and is nothing and stuff like that and they cause
4
10704
by: Steph. | last post by:
I have a List view displaying data in Detail mode with several columns. How I can get the column index the user clicked on ? (when user click on an item inside the ListView, not on a column hearder..) Thanks for any help !
13
2533
by: venkatesh | last post by:
hai I need to know about array out of bound error which is thought by our lecturer .she thought that when u gross the intialially specified size it will show that error,but when I am working on my computer it shows only the value which is allocated after the declaration?
0
2382
by: Beaker | last post by:
I am having some trouble with an array object and a web service I have. I have a farly simple user object public class User { private Guid myUserId; public Guid UserId { get { return myUserId; }
7
2627
by: polas | last post by:
Afternoon everyone. I have a quick question about standard C. Generally speaking, in my experience, whenever one accesses an array there is never any bounds checking done (either statically during compilation or dynamically during runtime.) However, I was wondering if whether there is anything defined in the standard about this. The reason for this is I have some code conforming to ANSI C99 and wish to write to both arrays and a block...
1
1523
by: Madmartigan | last post by:
Hi I'd like to know how to inlcude a check to make sure the index requested is not out of bounds in C#. In the following code I have created an array to store ten numbers at most. The array must be accessible using an Indexer. In the Indexer I would like to include the check. using System; class Numbers {
1
10351
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
10096
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
9174
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
7638
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
6866
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
5534
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
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.