segmentation fault in data processing code
#include <stdio.h>
#include<stdio.h>
#include <ctype.h>
/**
* Display the contents of a stream as hexadecimal bytes and text.
* @param file pointer to a binary stream
* @return the number of bytes in the file read
*/
size_t hexdump(FILE *file,FILE *fp,FILE *fp1)
{
unsigned char data[16]开发者_开发百科;
size_t i, j, size, count = 0;
/*
* Heading
*/
fputs(" ", stdout); /* skip address area */
for ( i = 0; i < sizeof data / sizeof *data; ++i )
{
printf("+%lX ", (long unsigned)i);
}
puts("Text");
/*
* Body
*/
do {
/* Read some data. */
size = fread(data, sizeof *data, sizeof data / sizeof *data, file);
if ( size )
{
/* Print the base address. */
printf("%08lX ", (long unsigned)count);
fprintf(fp,"%08lX",(long unsigned)count);
count += size; /* adjust the base address */
/* Print the characters' hex values. */
for ( i = 0; i < size; ++i )
{
printf("%02X ", data[i]);
fprintf(fp1,"%02X",data[i]);
}
/* Pad the hex values area if necessary. */
for ( ++i; i <= sizeof data / sizeof *data; ++i )
{
fputs(" ", stdout);
}
/* Print the characters (use '.' for non-printing characters). */
/* for ( j = 0; j < size; j++ )
{
putchar(isprint(data[j]) ? data[j] : '.');
}*/
putchar('\n');
}
} while ( size == sizeof data / sizeof *data ); /* Break on partial count. */
return count;
}
int main(void)
{
char filename[20] ;/* may not work on everywhere */
char filename1[20];
char filename2[20];
printf("enter the filename\n");
scanf("%s",filename);
printf("enter the filename to store address\n");
scanf("%s",filename1);
printf("enter the filename to store data\n");
scanf("%s",filename2);
FILE *file = fopen(filename, "rb");
FILE *fp= fopen(filename1,"wb");
FILE *fp1=fopen(filename2,"rb");
if ( file != NULL )
{
printf("%lu bytes\n", (long unsigned)hexdump(file,fp,fp1));
fclose(file);
fclose(fp);
fclose(fp1);
}
else
{
perror(filename);
}
return 0;
}
When executing the code above, I got a segmentation fault. Here's the output:
+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F Text
Segmentation fault
What could be reason for this?
FILE *fp1=fopen(filename2,"rb");
You open fp1 for reading. Yet you write to it. Change it to
FILE *fp1=fopen(filename2,"wb");
Firstly, it is usual to use sizeof as sizeof(a)
rather than sizeof a
. In fact I didn't realise you could even use sizeof without parenthesese.
Secondly, I am unaware as to the precedence of sizeof so don't know what result sizeof data / sizeof *data
gives. Try doing sizeof(data)/sizeof(*data)
instead. It could be being interpreted as sizeof(data/sizeof(*data))
. I suspect it isn't, but in any case it makes it all more readable and is good practice.
Lastly, are you sure fp
is non-NULL? You don't check your input parameters (always a good idea to do so) so there is no guarantee that it isn't NULL and if it is NULL you'll get a segfault at exactly where you seem tobe getting one.
精彩评论