473,657 Members | 2,595 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

K&R2 , exercise 7.6

PURPOSE :: see statement in comments

GOT: Segmentation Fault

I guess the segfault is sourced in the compile-time warning but I am
giving a char* to the function already.


/* K&R2, section 7.7, exercise 7.6
*
* write a program to compare 2 files, printing that first line
* where they differ.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum MAXSIZE { ARRSIZE=1000 };

void compare_files( FILE*, FILE* );
void print_line( char* );
int main( int argc, char* argv[] )
{
FILE *pf1, *pf2;

if( argc !=3 )
{
fprintf( stderr, "You iDiOT, I expect 2 files as input. \n" );
exit(EXIT_FAILU RE);
}
/* open files */
pf1 = fopen( *++argv, "r" );
pf2 = fopen( *++argv, "r" );

/* error check */
if( pf1 == NULL || pf2 == NULL )
{
fprintf( stderr, "error opening files\n");
exit(EXIT_FAILU RE);
}
else
{
compare_files( pf1,pf2 );
}

/* don't forget to close the files */
fclose( pf1 );
fclose( pf2 );
return 0;
}

/* compare 2 files */
void compare_files( FILE* pf1, FILE* pf2 )
{
int c1, c2, match;
char *line1, *line2;
char *begin_line1, *begin_line2;

match = 1;

while( ((line1 = fgets( line1, ARRSIZE, pf1 )) != NULL) ||
((line2 = fgets( line2, ARRSIZE, pf2 )) != NULL))
{
begin_line1 = line1;
begin_line2 = line2;

for( c1 = *line1, c2 = *line2; c1 != '\0' && c2 != '\0'; ++line1,
++line2 )
{
if ( c1 != c2 )
{
match = 0;
print_line( begin_line1 );
printf("\n-----------------------\n"); print_line( begin_line2 );
}
}
}
}

void print_line( char* line )
{
printf("%s\n", *line++);
}

=============== === OUTPUT =============== =======
[arnuld@raj C]$ gcc -ansi -pedantic -Wall -Wextra 7-6.c
7-6.c: In function `print_line':
7-6.c:88: warning: format argument is not a pointer (arg 2)

[arnuld@raj C]$ ./a.out
You iDiOT, I expect 2 files as input.

[arnuld@raj C]$ ./a.out 7-6.c 5-4.c
Segmentation fault
--
http://lispmachine.wordpress.com/
my email ID is at the above address

Jun 27 '08 #1
82 2794
arnuld said:
PURPOSE :: see statement in comments

GOT: Segmentation Fault
<snip>
int c1, c2, match;
char *line1, *line2;
Where do these point? (Hint: nowhere in particular.)
char *begin_line1, *begin_line2;

match = 1;

while( ((line1 = fgets( line1, ARRSIZE, pf1 )) != NULL) ||
((line2 = fgets( line2, ARRSIZE, pf2 )) != NULL))
They certainly don't point to ARRSIZE bytes of memory that you have the
right to update.

<snip>
void print_line( char* line )
{
printf("%s\n", *line++);
void print_line(cons t char *line)
{
puts(line);
}

--
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
On Mon, 21 Apr 2008 10:02:16 +0000, Richard Heathfield wrote:
arnuld said:
Where do these point? (Hint: nowhere in particular.)

OK, here is the 2nd version:
/* K&R2, section 7.7, exercise 7.6
*
* write a program to compare 2 files, printing that first line
* where they differ.
*
* version 1.1
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum MAXSIZE { ARRSIZE=1000 };

void compare_files( FILE*, FILE* );
void print_line( const char* );
int main( int argc, char* argv[] )
{
FILE *pf1, *pf2;

if( argc !=3 )
{
fprintf( stderr, "You iDiOT, I expect 2 files as input. \n" );
exit(EXIT_FAILU RE);
}
/* open files */
pf1 = fopen( *++argv, "r" );
pf2 = fopen( *++argv, "r" );

/* error check */
if( pf1 == NULL || pf2 == NULL )
{
fprintf( stderr, "error opening files\n");
exit(EXIT_FAILU RE);
}
else
{
compare_files( pf1,pf2 );
}

/* don't forget to close the files */
fclose( pf1 );
fclose( pf2 );
return 0;
}

/* compare 2 files */
void compare_files( FILE* pf1, FILE* pf2 )
{
int match;
char c1, c2;
char line1[ARRSIZE];
char line2[ARRSIZE];
char *begin_line1, *begin_line2, *p1, *p2;
match = 1;

while( (fgets( line1, ARRSIZE, pf1 ) != NULL) ||
(fgets( line2, ARRSIZE, pf2 ) != NULL))
{
begin_line1 = line1;
begin_line2 = line2;

p1 = line1;
p2 = line2;
for( c1 = *p1, c2 = *p2; c1 != '\0' && c2 != '\0'; ++p1, ++p2 )
{
if ( c1 != c2 )
{
match = 0;
print_line( begin_line1 );
printf("\n-----------------------\n"); print_line( begin_line2 );
}
}
}
}

void print_line( const char* line )
{
while( *line != '\0')
{
puts(*line++);
}
}

=============== = OUTPUT =============== ========

[arnuld@raj C]$ gcc -ansi -pedantic -Wall -Wextra 7-6.c
7-6.c: In function `print_line':
7-6.c:96: warning: passing arg 1 of `puts' makes pointer from integer
without a cast
[arnuld@raj C]$ ./a.out 7-6.c replace-blanks.c Segmentationfau lt
[arnuld@raj C]$



--
http://lispmachine.wordpress.com/
my email ID is at the above address

Jun 27 '08 #3
arnuld wrote:
void print_line( const char* line )
{
while( *line != '\0')
{
puts(*line++);
}
}

=============== = OUTPUT =============== ========

[arnuld@raj C]$ gcc -ansi -pedantic -Wall -Wextra 7-6.c
7-6.c: In function `print_line':
7-6.c:96: warning: passing arg 1 of `puts' makes pointer from integer
without a cast
[arnuld@raj C]$ ./a.out 7-6.c replace-blanks.c Segmentationfau lt
[arnuld@raj C]$
Ask yourself: what does `puts` accept as an parameter? What is
the type of the expression `*line++`? Are C characters a kind
of integer? Do you really expect an integer to be freely and
automatically converted to an integer?

--
"It took a very long time, much longer than the most /Sector General/
generous estimates."

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Jun 27 '08 #4
arnuld wrote:
>On Mon, 21 Apr 2008 10:02:16 +0000, Richard Heathfield wrote:
>arnuld said:
>Where do these point? (Hint: nowhere in particular.)


OK, here is the 2nd version:
/* K&R2, section 7.7, exercise 7.6
*
* write a program to compare 2 files, printing that first line
* where they differ.
*
* version 1.1
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum MAXSIZE { ARRSIZE=1000 };

void compare_files( FILE*, FILE* );
void print_line( const char* );
int main( int argc, char* argv[] )
{
FILE *pf1, *pf2;

if( argc !=3 )
{
fprintf( stderr, "You iDiOT, I expect 2 files as input. \n" );
exit(EXIT_FAILU RE);
}
/* open files */
pf1 = fopen( *++argv, "r" );
pf2 = fopen( *++argv, "r" );

/* error check */
if( pf1 == NULL || pf2 == NULL )
{
fprintf( stderr, "error opening files\n");
exit(EXIT_FAILU RE);
}
else
{
compare_files( pf1,pf2 );
}

/* don't forget to close the files */
fclose( pf1 );
fclose( pf2 );
return 0;
}

/* compare 2 files */
void compare_files( FILE* pf1, FILE* pf2 )
{
int match;
char c1, c2;
char line1[ARRSIZE];
char line2[ARRSIZE];
char *begin_line1, *begin_line2, *p1, *p2;
match = 1;

while( (fgets( line1, ARRSIZE, pf1 ) != NULL) ||
(fgets( line2, ARRSIZE, pf2 ) != NULL))
{
begin_line1 = line1;
begin_line2 = line2;

p1 = line1;
p2 = line2;
for( c1 = *p1, c2 = *p2; c1 != '\0' && c2 != '\0'; ++p1, ++p2 )
{
if ( c1 != c2 )
{
match = 0;
print_line( begin_line1 );
printf("\n-----------------------\n"); print_line( begin_line2
); }
}
}
}

void print_line( const char* line )
{
while( *line != '\0')
{
puts(*line++);
}
}

=============== = OUTPUT =============== ========

[arnuld@raj C]$ gcc -ansi -pedantic -Wall -Wextra 7-6.c
7-6.c: In function `print_line':
7-6.c:96: warning: passing arg 1 of `puts' makes pointer from integer
without a cast
What does that warning tell you?
[arnuld@raj C]$ ./a.out 7-6.c replace-blanks.c Segmentationfau lt
[arnuld@raj C]$
You lied to your compiler (and he spotted it and warned you about it) and he
got his revenge...

Bye, Jojo
Jun 27 '08 #5
On Mon, 21 Apr 2008 11:35:00 +0100, Chris Dollin wrote:

Ask yourself: what does `puts` accept as an parameter? What is
the type of the expression `*line++`?

K&R2 Appendix B, page 247:

"int puts( const char *s )

puts writes the string s and the newline to stdout. It returns EOF
if an error occurs, non-negative otherwise"
Now there are no strings in C. We have arrays of characters. It is same
like printf() which accepts %s as an array of chars. So <lineis a single
line of input form file stored into an array of chars.

Are C characters a kind
of integer? Do you really expect an integer to be freely and
automatically converted to an integer?
that was my mistake, my typo(s), I think I am getting sleepy. I just
recently shifted from North-India to South-India and I had to change my
food-habits. I am not able to get any food I used to eat from last 27
years (since I was born). So I have lots of difficulties in living a
normal daily routine here.


--
http://lispmachine.wordpress.com/
my email ID is at the above address

Jun 27 '08 #6
arnuld said:
>On Mon, 21 Apr 2008 11:35:00 +0100, Chris Dollin wrote:

>Ask yourself: what does `puts` accept as an parameter? What is
the type of the expression `*line++`?


K&R2 Appendix B, page 247:

"int puts( const char *s )

puts writes the string s and the newline to stdout. It returns
EOF
if an error occurs, non-negative otherwise"
I don't know whether you noticed, but I gave you a working version of
print_line - and you appear to have broken it again.
>

Now there are no strings in C.
Wrong. In C, a string is a contiguous sequence of characters, terminated by
the first null character.
We have arrays of characters. It is same
like printf() which accepts %s as an array of chars.
Wrong. printf interprets %s as meaning "the parameter matching this format
specifier is a ##pointer## to the first character in a contiguous sequence
of characters that is terminated by a null character" - in other words, %s
means "I'm giving you a string".

<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 #7
On Mon, 21 Apr 2008 10:02:16 +0000, Richard Heathfield wrote:
>arnuld wrote:
int c1, c2, match;
char *line1, *line2;
Where do these point? (Hint: nowhere in particular.)

okay, here is the 3rd version of the program. It compiles and runs, the
only thing is semantic-bug, it always does one thing, no matter whether 2
files are same or different:

/* K&R2, section 7.7, exercise 7.6
*
* write a program to compare 2 files, printing that first line
* where they differ.
*
* version 1.2
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum MAXSIZE { ARRSIZE=1000 };

void compare_files( FILE*, FILE* );
void print_line( const char* );
int main( int argc, char* argv[] )
{
FILE *pf1, *pf2;

if( argc !=3 )
{
fprintf( stderr, "You iDiOT, I expect 2 files as input. \n" );
exit(EXIT_FAILU RE);
}
/* open files */
pf1 = fopen( *++argv, "r" );
pf2 = fopen( *++argv, "r" );

/* error check */
if( pf1 == NULL || pf2 == NULL )
{
fprintf( stderr, "error opening files\n");
exit(EXIT_FAILU RE);
}
else
{
compare_files( pf1,pf2 );
}

/* don't forget to close the files */
fclose( pf1 );
fclose( pf2 );
return 0;
}

/* compare 2 files */
void compare_files( FILE* pf1, FILE* pf2 )
{
int match;
char c1, c2;
char line1[ARRSIZE];
char line2[ARRSIZE];
const char *begin_line1, *begin_line2, *p1, *p2;
match = 1;

while( (fgets( line1, ARRSIZE, pf1 ) != NULL) || (fgets( line2, ARRSIZE, pf2 ) != NULL))
{
begin_line1 = line1;
begin_line2 = line2;

p1 = line1;
p2 = line2;
for( c1 = *p1, c2 = *p2; c1 != '\0' && c2 != '\0'; ++p1, ++p2 )
{
if ( c1 != c2 )
{
match = 0;
print_line( begin_line1 );
printf("\n-----------------------\n");
print_line( begin_line2 );
return;
}
}
}
}

void print_line( const char* line )
{
while( *line != '\0')
{
putchar(*line++ );
}
}

--
http://lispmachine.wordpress.com/
my email ID is at the above address

Jun 27 '08 #8
In article <pa************ *************** *@NoPain.Rome>,
arnuld <No****@NoPain. Romewrote:
>Wrong. In C, a string is a contiguous sequence of characters, terminated
by the first null character.
>but these 2 are different:

char arr[] = "Richard";
char* pc = "Richard";

both are contiguous sequence of characters ended by '\0'.
And they are both strings.
>Wrong. printf interprets %s as meaning "the parameter matching this
format specifier is a ##pointer## to the first character in a contiguous
sequence of characters that is terminated by a null character" - in
other words, %s means "I'm giving you a string".
>you can never use the pc for %s in printf().
What do you mean by "the pc"? Do you mean the variable pc declared
above? If so, you can certainly print it with %s.

-- Richard
--
:wq
Jun 27 '08 #9
arnuld wrote:
>On Mon, 21 Apr 2008 11:57:59 +0000, Richard Heathfield wrote:
>Wrong. In C, a string is a contiguous sequence of characters,
terminated by the first null character.

but these 2 are different:

char arr[] = "Richard";
char* pc = "Richard";

both are contiguous sequence of characters ended by '\0'.
pc is a pointer to a (read-only) string
arr is an array containing a (modifyable) string
>Wrong. printf interprets %s as meaning "the parameter matching this
format specifier is a ##pointer## to the first character in a
contiguous sequence of characters that is terminated by a null
character" - in other words, %s means "I'm giving you a string".


you can never use the pc for %s in printf().
Nonsense. In both cases printf only sees a pointer to char and prints that
up to the terminating \0.
Thats what I meant, there
are no strings, only arrays of chars. I tried to print the pc but all
I got was:
^A^M^D @#
They you must have done something severly wrong.

Bye, Jojo
Jun 27 '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
2287
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
4751
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
1564
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
1725
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
3740
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
8310
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
8827
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...
1
8503
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
8605
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
7333
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
6167
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
5632
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
4158
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
1957
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.