473,624 Members | 2,601 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

K&R2, exercise 4-2

STATEMENT: Write the function strindex(s, t), which returns the position of the
rightmost occurence of t in s, or -1 if there is none.

PURPOSE: this program prints the index of the rightmost match on the line.
The match we have to find is a char array named pattern. We also print out
the number of matches we have found. We will take the input from
command-line.
PROBLEM: Segmentation Fault

The programe compiles fine but at run-time it segfaults :(
here is my solution which is a little modified version of the example
provided in the same section:

/* Exercise # 4.1 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum MAXSIZE { ARR_SIZE = 1000 };

int getline( char current_line[], int max );
int str_index( char current_line[], char search_for[] );

char pattern[] = "term";

int match_num;
int main( void )
{
char current_line[ARR_SIZE];
int matched_idx, idx;

idx = 0;
while( getline(current _line, ARR_SIZE) 0 )
{
if( (matched_idx = str_index(curre nt_line, pattern)) >= 0 )
{
printf("\n%d matches, \n%d is the last to match", match_num, matched_idx);
}
}

return 0;

}
/* takes a line as input and returns the length of the line */
int getline( char s[], int max )
{
int c, i;

for( i = 0; ( (c = getchar()) != EOF && (c != '\n') && (--max 0) ); ++i )
{
s[i] = c;
}

if( c == '\n' )
{
s[i++] = '\n';
}

s[i] = '\0';

return i;
}
/* search for a pattern in the line, will save every index position of
source string where the pattern starts to match. For string the index we
use an array of ints. we then return the last element of array which is the
index of the rightmost match. We also return the number of matches we have
found using an int match_num.
*/
int str_index( char s[], char p[] )
{
int i, j, k;
int idx, last_match;
int saved_pos[ARR_SIZE];
memset( saved_pos, '\0', sizeof( saved_pos ));

idx = 0;
match_num = 0;
for( i = 0; s[i] != '\0'; ++i )
{
for( k = 0, j = i; p[k] != '\0' ; ++k, ++j )
{
if( s[j] != p[k] )
{
break;
}
}

if( (k 0) && p[k] == '\0' )
{
saved_pos[idx] = i;
++match_num;
}
}

last_match = sizeof(saved_po s) - 2;
/* it checks whether we have any match or not. If we do not have any match
* then we have nothing in array */
if( saved_pos[0] )
{
return saved_pos[last_match];
}
else
{
return -1;
}
}
=========== OUTPUT =============
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra 4-1.c
/home/arnuld/programs/C $ ./a.out
terminal
and no one
and this
term
and Xterminal
segmentation fault
/home/arnuld/programs/C $
Apr 3 '08 #1
15 1803
On Thu, 03 Apr 2008 19:14:49 +0530, arnuld wrote:
last_match = sizeof(saved_po s) - 2;
/* it checks whether we have any match or not. If we do not have any
match
* then we have nothing in array */
if( saved_pos[0] )
{
return saved_pos[last_match];
}
that was the source of trouble. I changed it to this:
if( saved_pos[0] )
{
return saved_pos[match_num - 1];
}

and I got a new bug:
[arnuld@raj C]$ gcc -ansi -pedantic -Wall -Wextra 4-1.c
[arnuld@raj C]$ ./a.out
and no TERM
term
and term

1 matches,
4 is the last to match
how about this tErm
nope
the terminal is the xterm and urxvt term

3 matches,
0 is the last to match[arnuld@raj C]$
whats the problem now ?

Apr 3 '08 #2
arnuld said:

<snip>
PROBLEM: Segmentation Fault

The programe compiles fine but at run-time it segfaults :(
<snip>
int str_index( char s[], char p[] )
{
int i, j, k;
int idx, last_match;
int saved_pos[ARR_SIZE];
<snip>
>
last_match = sizeof(saved_po s) - 2;
This doesn't do what you think. sizeof saved_pos gives the size, in bytes,
of the array. That's fine if ints are 1 byte in size, which they can be,
but it doesn't seem to be the case on your system.

What you meant to write was:

last_match = sizeof saved_pos / sizeof saved_pos[0] - 2;

This fixes your problem.

And in case anyone's curious, the only use I made of gdb for finding this
bug was to get a backtrace, from which the problem was immediately
obvious.

--
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
Apr 3 '08 #3
arnuld said:

<snip>
> {
return saved_pos[last_match];
}

that was the source of trouble.
No, that was the symptom, not the cause. See my other reply.

--
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
Apr 3 '08 #4
On Thu, 03 Apr 2008 19:22:29 +0530, Richard Heathfield wrote:

This doesn't do what you think. sizeof saved_pos gives the size, in
bytes, of the array. That's fine if ints are 1 byte in size, which they
can be, but it doesn't seem to be the case on your system.
your way/idea of telling the problem is very clear. I never expected that
from the author of a book like "C Unleashed". NO, I have not read the book
but heard about its toughness and harder ideas.

What you meant to write was:

last_match = sizeof saved_pos / sizeof saved_pos[0] - 2;

This fixes your problem.
I got a new one:

[arnuld@raj C]$ ./a.out
term
term
Xterm

1 matches,
Position 1 is the last to match

[arnuld@raj C]$ ./a.out
this terminal

1 matches,
Position 1 is the last to match
[arnuld@raj C]$
look at the output. program is not reading the position 0 and always saying
that position 1 is th elast to match. I think I have modified the file a
little. you can check the whole source here:

http://pastebin.ca/969121
And in case anyone's curious, the only use I made of gdb for finding
this bug was to get a backtrace, from which the problem was immediately
obvious.
Oh... I never used gdb. I think I need to read the manual to start using
it.

Apr 3 '08 #5
Richard Heathfield <rj*@see.sig.in validwrites:
arnuld said:

<snip>
>PROBLEM: Segmentation Fault

The programe compiles fine but at run-time it segfaults :(

<snip>
>int str_index( char s[], char p[] )
{
int i, j, k;
int idx, last_match;
int saved_pos[ARR_SIZE];

<snip>
>>
last_match = sizeof(saved_po s) - 2;

This doesn't do what you think. sizeof saved_pos gives the size, in bytes,
of the array. That's fine if ints are 1 byte in size, which they can be,
but it doesn't seem to be the case on your system.

What you meant to write was:

last_match = sizeof saved_pos / sizeof saved_pos[0] - 2;

This fixes your problem.
I am not sure if you are joking. It fixes the problem only for some
very limited meanings of either "fix" or "problem".

--
Ben.
Apr 3 '08 #6
arnuld <oo***@poonga.c omwrites:
>On Thu, 03 Apr 2008 19:14:49 +0530, arnuld wrote:
> last_match = sizeof(saved_po s) - 2;
/* it checks whether we have any match or not. If we do not have any
match
* then we have nothing in array */
if( saved_pos[0] )
{
return saved_pos[last_match];
}

that was the source of trouble. I changed it to this:
if( saved_pos[0] )
{
return saved_pos[match_num - 1];
}

and I got a new bug:
You have a few. I'll take only one that I can illustrate from the
fragment above: you can't tell if there is or is not a match by
testing saved_pos[0] because there match might be a first match at
position zero. Now, as it happens, you store all the match positions
in index 0 of this array because you don't increment idx (not shown)
so this bug only shows up when the first and last match are at
position zero.

I would suggest you don't try to store the matches. Try to find a way
that does not involve remembering them all, just to return the
right-most one.

--
Ben.
Apr 3 '08 #7
Ben Bacarisse said:
Richard Heathfield <rj*@see.sig.in validwrites:
<snip>
>>
What you meant to write was:

last_match = sizeof saved_pos / sizeof saved_pos[0] - 2;

This fixes your problem.

I am not sure if you are joking. It fixes the problem only for some
very limited meanings of either "fix" or "problem".
Well, okay, it fixes the segfault, anyway. The segfault was caused by his
violating the bounds of the saved_pos array a few lines further on,
because he was calculating the offset not in objects but in bytes. I'm not
claiming that my fix removes *all* the bugs from his program, but it
removes *this* bug.

If you don't find that this answer deals with your point, perhaps you could
explain further what you are getting at?

--
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
Apr 3 '08 #8
On Thu, 03 Apr 2008 19:46:34 +0530, Ben Bacarisse wrote:
You have a few. I'll take only one that I can illustrate from the
fragment above: you can't tell if there is or is not a match by testing
saved_pos[0] because there match might be a first match at position
zero. Now, as it happens, you store all the match positions in index 0
of this array because you don't increment idx (not shown) so this bug
only shows up when the first and last match are at position zero.

I would suggest you don't try to store the matches. Try to find a way
that does not involve remembering them all, just to return the
right-most one.

HEY.. thanks :) , how about this, works perfectly fine. Tell me if I have
any more bugs left:

/* Exercise # 4.1 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum MAXSIZE { ARR_SIZE = 1000 };

int getline( char current_line[], int max );
int str_index( char current_line[], char search_for[] );

char pattern[] = "term";

int match_num;
int main( void )
{
char current_line[ARR_SIZE];
int matched_idx, idx;

idx = 0;
while( getline(current _line, ARR_SIZE) 0 )
{
if( (matched_idx = str_index(curre nt_line, pattern)) >= 0 )
{
printf("\n%d matches -- ", match_num);
if( match_num )
{
printf("Positio n %d is the last to match\n\n", matched_idx);
}
}
}

return 0;

}
/* takes a line as input and returns the length of the line */
int getline( char s[], int max )
{
int c, i;

for( i = 0; ( (c = getchar()) != EOF && (c != '\n') && (--max 0) ); ++i )
{
s[i] = c;
}

if( c == '\n' )
{
s[i++] = '\n';
}

s[i] = '\0';

return i;
}
/* search for a pattern in the line, will save every index position of source
string where the pattern starts to match. For string the index we use an
array of ints. we then return the last element of array which is the
index of the rightmost match. We also return the number of matches we have
found using an int match_num.
*/
int str_index( char s[], char p[] )
{
int i, j, k;
int idx, match_pos;
idx = 0;
match_num = 0;
for( i = 0; s[i] != '\0'; ++i )
{
for( k = 0, j = i; p[k] != '\0' ; ++k, ++j )
{
if( s[j] != p[k] )
{
break;
}
}

if( (k 0) && p[k] == '\0' )
{
++match_num;
match_pos = i;
}
}

/* it checks whether we have any match or not. */
if( match_num )
{
return match_pos;
}
else
{
return -1;
}
}
========== OUTPUT ============
[arnuld@raj C]$ gcc -ansi -pedantic -Wall -Wextra -ggdb 4-1.c
[arnuld@raj C]$ ./a.out
and this
and that
9843788327#&&$^ $^$^^$TER%%^
TERM
term

1 matches -- Position 0 is the last to match

term and term and term\0

3 matches -- Position 18 is the last to match

[arnuld@raj C]$


Apr 3 '08 #9
Richard Heathfield <rj*@see.sig.in validwrites:
Ben Bacarisse said:
>Richard Heathfield <rj*@see.sig.in validwrites:
<snip>
>>>
What you meant to write was:

last_match = sizeof saved_pos / sizeof saved_pos[0] - 2;

This fixes your problem.

<snipIt fixes the problem only for some
very limited meanings of either "fix" or "problem".

Well, okay, it fixes the segfault, anyway.
Right. I thought that is maybe what you meant.

--
Ben.
Apr 3 '08 #10

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

Similar topics

12
2164
by: Chris Readle | last post by:
Ok, I've just recently finished a beginning C class and now I'm working through K&R2 (alongside the C99 standard) to *really* learn C. So anyway, I'm working on an exercise in chapter one which give me strange behavior. Here is the code I've written: /****************************************************************************** * K&R2 Exercise 1-9 * Write a program to copy its input to its output, replacing strings of blanks * with a...
16
2267
by: Josh Zenker | last post by:
This is my attempt at exercise 1-10 in K&R2. The code looks sloppy to me. Is there a more elegant way to do this? #include <stdio.h> /* copies input to output, printing */ /* series of blanks as a single one */ int main() { int c;
2
2286
by: arnuld | last post by:
there is a solution on "clc-wiki" for exercise 1.17 of K&R2: http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_17 i see this uses pointers whereas K&R2 have not discussed pointers yet. i have created a solution myself by modifying the example programme of section 1.19. i tried to find the source-code of K&R2 using Google. i found the home
8
4750
by: arnuld | last post by:
i have created a solutions myself. it compiles without any trouble and runs but it prints some strange characters. i am not able to find where is the trouble. --------------------------------- PROGRAMME -------------------------------- /* K&R2 section 1.9 exercise 1.19
4
1563
by: arnuld | last post by:
as i said, i have restarted the book because i overlooked some material. i want to have some comments/views on this solution. it runs fine, BTW. ------------------ PROGRAMME -------------- /* K&R2 section 1.5.3, exercise 1-8 write a programme to count blanks, tabs and newlines */
16
1799
by: arnuld | last post by:
i have created solution which compiles and runs without any error/ warning but it does not work. i am not able to understand why. i thought it is good to post my code here for correction before looking at CLC-Wiki for K&R2 solutions: --------------- PROGRAMME ------------ /* K&R2 section 1.5.3, exercise 1-9 STATEMENT: write a programme to copy its input to output replacing
19
2395
by: arnuld | last post by:
this programme runs without any error but it does not do what i want it to do: ------------- PROGRAMME -------------- /* K&R2, section 1.6 Arrays; Exercise 1-13. STATEMENT: Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical
5
2914
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any compile-error BUT it has a semantic BUG: what i WANT: I want it to produce a "horizontal histogram" which tells how many characters were in the 1st word, how many characters were in the second word by writing equal number of stars, *, at the...
16
1724
by: arnuld | last post by:
i am not able to make it work. it compiles without any error but does not work: what i WANTED: 1.) 1st we will take the input in to an array. (calling "getline" in "main") 2.) we will print that input array on terminal. (in "main") 3.) we will reverse the array. (calling "reverse" in "main") 4.) we will print that reversed array. (in "main")
88
3732
by: santosh | last post by:
Hello all, In K&R2 one exercise asks the reader to compute and print the limits for the basic integer types. This is trivial for unsigned types. But is it possible for signed types without invoking undefined behaviour triggered by overflow? Remember that the constants in limits.h cannot be used.
0
8249
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
8633
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
8348
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
8493
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
7176
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
6112
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
5570
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
4084
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...
2
1493
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.