473,408 Members | 2,832 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Newbie question: Why does this work?

Hi all!
This is most certainly a total newbie question, but why doesn't the
following code cause a segfault?

void insertion_sort(int a[], int length)
{
int i;
for (i=0; i < length; i++)
{
int j, v = a[i];
for (j = i - 1; j >= 0; j--)
{
if (a[j] <= v) {
cout << a[j] << " <= " << v << endl;
break;
}
a[j + 1] = a[j];
}
a[j + 1] = v;
}
}

IMHO the segfault should occur at line 9 as on the first pass through
the first for-loop i = o ergo j is -1 causing a[j] to provoke a
segfault.

Thanks in advance and excuse me for asking such a dumb question
Jun 27 '08 #1
12 1807
Ph*******************@gmail.com said:
Hi all!
This is most certainly a total newbie question, but why doesn't the
following code cause a segfault?

void insertion_sort(int a[], int length)
{
int i;
for (i=0; i < length; i++)
{
int j, v = a[i];
for (j = i - 1; j >= 0; j--)
{
if (a[j] <= v) {
This isn't broken because, first time through, i = 0, so j becomes i - 1 =
-1, which is not >= 0, so the loop body is skipped completely.
cout << a[j] << " <= " << v << endl;
Just for the record, this is a C newsgroup, not a C++ newsgroup.

<snip>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #2
Ph*******************@gmail.com wrote:
Hi all!
This is most certainly a total newbie question, but why doesn't the
following code cause a segfault?

void insertion_sort(int a[], int length)
{
int i;
for (i=0; i < length; i++)
{
int j, v = a[i];
for (j = i - 1; j >= 0; j--)
{
if (a[j] <= v) {
cout << a[j] << " <= " << v << endl;
break;
}
a[j + 1] = a[j];
}
a[j + 1] = v;
}
}

IMHO the segfault should occur at line 9 as on the first pass through
the first for-loop i = o ergo j is -1 causing a[j] to provoke a
segfault.

Thanks in advance and excuse me for asking such a dumb question
The second for loop will be entered only when it's condition is true,
i.e., only when j is >= 0. This will not happen after the first
iteration of the outer loop. During the second iteration of the outer
loop, j will be initialised to 0 so the code under the inner for loop
will be executed.

Jun 27 '08 #3
In article <64**********************************@a23g2000hsc. googlegroups.com>,
Ph*******************@gmail.com <Ph*******************@gmail.comwrote:
>This is most certainly a total newbie question, but why doesn't the
following code cause a segfault?
>void insertion_sort(int a[], int length)
{
int i;
for (i=0; i < length; i++)
{
int j, v = a[i];
for (j = i - 1; j >= 0; j--)
{
if (a[j] <= v) {
cout << a[j] << " <= " << v << endl;
The above line will not compile, as you have not defined a variable
named 'cout', nor a variable named 'endl'. Furthermore, left-shifting
a pointer by a value, or a value by a pointer, is not a defined
operation in C. Perhaps in copying out the program for the posting,
you accidently pasted in a line from another window in which you
had something dealing with some other programming language such as
Rogaine ?

> break;
}
a[j + 1] = a[j];
}
a[j + 1] = v;
}
}
>IMHO the segfault should occur at line 9 as on the first pass through
the first for-loop i = o ergo j is -1 causing a[j] to provoke a
segfault.
When i = 0, and you start the for (j = i - 1; j >= 0; j--) loop,
then j -will- be initialized to -1, but the loop condition j >= 0
will be evaluated before any trips are taken through the loop, and will
be found to be false, so the loop will not be executed. The j >= 0
protects the loop from executing when j is not at least 0.
--
"Man's life is but a jest,
A dream, a shadow, bubble, air, a vapor at the best."
-- George Walter Thornbury
Jun 27 '08 #4
Ph*******************@gmail.com wrote:
IMHO the segfault should occur at line 9 as on the first pass through
the first for-loop i = o ergo j is -1 causing a[j] to provoke a
segfault.
Even if you had accessed outside the boundaries, that's undefined
behavior. There is no defined behavior for undefined behavior. That
includes segfaults or any other behavior.

Brian
Jun 27 '08 #5
>>>>"P" == Philipp Weissenbacher@gmail com
>>>><Ph*******************@gmail.comwrites:
PHi all! This is most certainly a total newbie question, but why
Pdoesn't the following code cause a segfault?

Because segfaults are a bonus, not a requirement.

Charlton
--
Charlton Wilbur
cw*****@chromatico.net
Jun 27 '08 #6
On 16 Mai, 21:01, Charlton Wilbur <cwil...@chromatico.netwrote:
>>>"P" == Philipp Weissenbacher@gmail com
<Philipp.Weissenbac...@gmail.comwrites:

PHi all! This is most certainly a total newbie question, but why
Pdoesn't the following code cause a segfault?

Because segfaults are a bonus, not a requirement.

Charlton

--
Charlton Wilbur
cwil...@chromatico.net
At first thanks for all the answers. And yes I'm actually using C++; I
just missed some couts. Sorry for that one.
@Roberson: I always thought a for loop does at lest one iteration
before checking the condition. Gotta reread that part ...
Jun 27 '08 #7
In article <a2**********************************@d77g2000hsb. googlegroups.com>,
Ph*******************@gmail.com <Ph*******************@gmail.comwrote:
>@Roberson: I always thought a for loop does at lest one iteration
before checking the condition. Gotta reread that part ...
No, the only iteration form that does at least one iteration before
checking the condition is "do until"

--
"I think Walter's legacy will be that of a man with a God-given
ability that got the most out of it at every possible chance."
-- Eddie Payton
Jun 27 '08 #8
"Ph*******************@gmail.com" <Ph*******************@gmail.comwrites:
This is most certainly a total newbie question, but why doesn't the
following code cause a segfault?

void insertion_sort(int a[], int length)
{
int i;
for (i=0; i < length; i++)
{
int j, v = a[i];
for (j = i - 1; j >= 0; j--)
{
if (a[j] <= v) {
cout << a[j] << " <= " << v << endl;
printf("%d <= %d\n", a[j], v); /* This is comp.lang.c. */
break;
}
a[j + 1] = a[j];
}
a[j + 1] = v;
}
}

IMHO the segfault should occur at line 9 as on the first pass through
the first for-loop i = o ergo j is -1 causing a[j] to provoke a
segfault.
Here's something you could have tried that probably would have avoided
the need to post the question:

By inserting a printf call at the beginning of the for loop:

printf("j = %d\n", j);

you could have seen that j never has the value -1 (which would leave
you to fix the logic problem that prevents the loop from being
executed at all).

Or you could do the equivalent in a debugger; the details of how to do
that are off-topic here, but should be in your debugger's documentation.

In any case, even if you did evaluate a[j] with j == -1, there's no
guarantee that it would cause a seg fault, or any other particular
result. The behavior is simply undefined (i.e., the C standard says
absolutely nothing about what might happen). It could cause a seg
fault, it could quietly access some piece of memory outside the array,
it could clobber something that causes your program to crash later.
It can't *really* make demons fly out of your nose (as the old joke
here goes), but if it did, it wouldn't be a violation of the C
standard.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #9
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <a2**********************************@d77g2000hsb. googlegroups.com>,
Ph*******************@gmail.com <Ph*******************@gmail.comwrote:
>>@Roberson: I always thought a for loop does at lest one iteration
before checking the condition. Gotta reread that part ...

No, the only iteration form that does at least one iteration before
checking the condition is "do until"
Or, if you happen to be programming in C <OT>or C++</OT>, "do while".
<OT>Pascal has "repeat until"; perhaps that's what you were thinking
of.</OT>

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #10
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.orgwrote:
>ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
>In article <a2**********************************@d77g2000hsb. googlegroups.com>,
>No, the only iteration form that does at least one iteration before
checking the condition is "do until"
>Or, if you happen to be programming in C <OT>or C++</OT>, "do while".
<OT>Pascal has "repeat until"; perhaps that's what you were thinking
of.</OT>
Nah, I just have a thick head today :(
--
'Roberson' is my family name; my given name is 'Walter'.
Jun 27 '08 #11
Ph*******************@gmail.com ha scritto:
cout <<
Bleah... ;-)
Jun 27 '08 #12
On 16 Mai, 21:52, rober...@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
In article <lnd4nmghpa....@nuthaus.mib.org>,
Keith Thompson <ks...@mib.orgwrote:
rober...@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <a235703d-62b9-4378-9518-8b15fc850...@d77g2000hsb.googlegroups.com>,
No, the only iteration form that does at least one iteration before
checking the condition is "do until"
Or, if you happen to be programming in C <OT>or C++</OT>, "do while".
<OT>Pascal has "repeat until"; perhaps that's what you were thinking
of.</OT>

Nah, I just have a thick head today :(
--
'Roberson' is my family name; my given name is 'Walter'.
@Walter: Thought this would be more polite. I'm a German native-
speaker and we have something called T-V distinction. The English
counterpart to "sie" appears to be calling someone with his family
name (at least for me) whereas calling someone by his given name
indicates a much closer relationship.
Jun 27 '08 #13

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

Similar topics

8
by: Tophurious | last post by:
First, let me start by saying I know what an overflow is (Too large of a value into something that can't hold it, i.e. 35000 into an int, or 0/0, etc). Now to the issue. I have a class that I am...
5
by: Banibrata Dutta | last post by:
Hi, I've gone through the list of "language differences" between 2.3 / 2.4 & 2.5 of CPython. I've spend around 2 weeks now, learning v2.5 of CPython, and I consider myself still very very...
2
by: David | last post by:
Hi list. I've never used unicode in a Python script before, but I need to now. I'm not sure where to start. I'm hoping that a kind soul can help me out here. My current (almost non-existant)...
2
by: Damfino | last post by:
Hi all, Newbie question here wrt defining a class that will work on bits read from a binary file. How would you go about doing it? As an example please look at the structure of my data given...
3
by: Tomislav Petrovic | last post by:
I have following table and a stored procedure in which I want to select rows from the table whose LOCAL_ID is one of the ids I give it in a_local_ids table which is input parameter and return...
2
by: Danny Ni | last post by:
Hi, I have the following on an aspx page: <asp:RadioButton ID="RadioButton1" runat="server" cssclass="radio" Text="Radio 1"/> This render as: <span class="radio"><input id="RadioButton1"...
6
by: LessPaul | last post by:
I recently discovered Python and see it as a great language to use for personal projects (and more). I made my living for over a decade as a coder in C, C++, ADA, Fortran, and Assembly before...
5
by: Dave | last post by:
I am new to Visual Web Developer 2005 Expres. I am using absolute positioning and every time I add a button control to my web form its width extends all the way to the edge of the page. IOW I...
8
by: jch | last post by:
Sorry for the newbie question but I'm trying to learn Visual Studio. I've got VS Express 2008 and I'm using visual basic. I'm trying to learn how to deploy a program so I've written a very basic...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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,...

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.