Why does the following code raise a SegFault. c(Linux)
This a code that would reverse the data of a document and s开发者_如何转开发ave it in the same document itself. However I am getting a Segmentation Fault.Please Help,I don't know why it gives a SegFault.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main (int argc,char* argv[])
{
int fd,n,i,j;
char* buf;
if(argc<2)
printf("USAGE: %s file-to-reverse.\n",argv[0]);
fd=open(argv[1], O_RDWR);
if(fd==-1)
printf("ERROR: Cannot reverse %s,file does not exist.\n",argv[1]);
i = 0;
j = n-1;
while(i < j)
{
read(fd,buf,n);
char ib = buf[i];
char jb = buf[j];
jb = i++;
ib = j--;
write(fd,buf,n);
}
free(buf);
close(fd);
}
EDIT1 I tried adding :
#include <sys/stat.h>
struct stat fs;
fstat(fd, &fs);
n= fs.st_size;
buf = malloc(n * sizeof (char));
but now it just duplicates the characters inside the document again and again instead of reversing them.
You don't allocate, nor initialize buf
.
You never initialized n
so it could be anything, even negative. Use fstat
or some other method to determine the size of the file and store that in n
.
Your buffer isn't allocated and n = 0 so you will try to read 0 chars. This should repair your code :
buf = malloc(10 * sizeof (char));
n = 10;
Resources :
- Wikipedia - malloc()
- linux.die.net - malloc()
- linux.die.net - read()
Regarding your second EDIT - your loop is wrong.
(1) Take the read & write out of the loop - that's why it keeps writing again & again.
(2) You need to seek back to the beginning of the file, otherwise you will just be appending the new data to the end of the file.
(3) You actually have to reverse the chars in the buffer before writing them out.
read(fd, buf, n);
while (i < j)
{
char t = buf[i];
buf[i] = buf[j];
buf[j] = t;
i++;
j--;
}
lseek(fd, 0, SEEK_SET);
write(fd, buf, n);
精彩评论