Why does the following code raise a SegFault. c(Linux)


This a code that would reverse the data of a document and save 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;

    printf("USAGE: %s file-to-reverse.\n",argv[0]);

    fd=open(argv[1], O_RDWR);
    printf("ERROR: Cannot reverse %s,file does not exist.\n",argv[1]);

    i = 0;
    j = n-1;

    while(i < j)

        char ib = buf[i];
        char jb = buf[j];

        jb = i++;
        ib = j--;



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.

4 Answers: 

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;


lseek(fd, 0, SEEK_SET);

write(fd, buf, n);

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 :


More Articles

node.js - Ubuntu + Nodejs + curl: (52) Empty reply from server

I have a nodejs process listening a port on my server:app.get('/statistic', function(req, res) { log_get_connection(req); getStatistic().then(statistic => { res.json(statistic); });});When I try to access it via curl being on the same machine:curl "http://127.0

Unable to Connect to mysql db through php in GCE instance with ubuntu

I'm a little bit frustrated with a problem I'm having in a system migration from AWS to GCE.I've an ec-2 instance running on amazon web services, perfectly working and configured.The problem is that google is offering a 100.000$ credit in a special plan for Startups, my company's CEO asks for a migr

node.js - webpack-dev-server does not create initial bundle on start

I have built a basic babel webpack starter project that i clone from git. The git repository has no dest/output/build folder nor does it have any initial build files. I am knew to webpack so i assumed that when the webpack-dev-server started up it would create a folder (in my case 'build') and do a

mysql - OTRS Fatal Error

hey i want to install otrs on an apache webserver with linux ubuntu.i created a new database with the otrs web installer but then I get the message: Can't open file /opt/otrs/Kernel/Config/Files/ZZZAAuto.pm.20881: Permission denied

node.js - Can't run NPM or ng build, or Apache in Ubuntu terminal

This question already has an answer here: env: bash\r: No such file or directory 4 answers Error with gradlew: /usr/bin/env: bash: No such file or directory 3 answe

shell - monitor for file then copy to another directory

I'm relatively new to unix scripting, so apologies for the newbie question.I need to create a script which will permanently run in the background, and monitor for a file to arrive in an FTP landing directory, then copy it to a different directory, and lastly remove the file from the original directo

c - Whats the difference between the two command lines? (SegFault)

I have written a code that maps to a shared memory location,so that the first program opens a shared memory block and stores some data in it.And the second program reads the shared data.Whats the difference between the two command lines:1. if(argc<2) { printf("USAGE:%s text-to-share\n",argv[0

linux - List out text files from given directory in unix

Writing shell script to sort text file data from given directory with for loop in ubuntu as: echo "Enter directory Name" read dr path= ` find /home/user -name $dr ` for x in ` ls *.txt $path ` do sort $x done echo "------Script finished-------"But this script is giving me er

linux - Segmentation fault due to lack of memory in C

This code gives me segmentation fault about 1/2 of the time:int main(int argc, char **argv) { float test[2619560]; int i; for(i = 0; i < 2619560; i++) test[i] = 1.0f;}I actually need to allocate a much larger array, is there some way of allowing the operating system to allow me ge

Unable to install LAMP (Linux, Apache, Mysql, PHP stack) on Ubuntu 16.04

I am trying to install LAMP server on my Ubuntu desktop. The problem I am facing is related to IP address of my laptop.While Setting Global ServerName to Suppress Syntax Warnings, as the documentation says here, when I am adding a ServerName directive, pointing to my server's public IP address in co