c - Encountering segment fault when printing out directories in Ubuntu


Question: 

I've been working on this code for a while and I can not figure out the problem. The idea is to print out all directories and sub directories from the given directory (hard coded for testing purposes). However, I keep getting a segmentation fault.

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

struct item
{
    char location[256];
    int level;
    int order;
    bool isExpanded;
    struct item *next;
};

struct item *headNode = NULL; 
struct item *currentNode = NULL;
struct item *loopNode = NULL;
static int currentLevel = 1;
static int currentOrder = 1;
bool finished = false;
char currentLocation[256];

void addNode(char location[256])
{
    struct item *ptr = (struct item*)malloc(sizeof(struct item));
    ptr->level = currentLevel;
    ptr->order = currentOrder;
    ptr->isExpanded = false;
    int x;
    for(x = 0; x < strlen(location); x++)
        ptr->location[x] = location[x];

    ptr->location[x] = '\0';
    ptr->next = NULL;

    currentNode->next = ptr;
    currentNode = ptr;
} 

int main(int argc, char *argv[])
{
    struct dirent *pDirent;
    DIR *pDir;
    argv[1] = "/home/collin/Documents";
    char temp[256];

    pDir = opendir (argv[1]);
    if (pDir == NULL) 
    {
        printf ("Cannot open directory '%s'\n", argv[1]);
        return 1;
    }
    closedir (pDir);

    headNode = (struct item*)malloc(sizeof(struct item));
    headNode->level = currentLevel;
    headNode->order = currentOrder;
    headNode->isExpanded = false;
    int x;
    for(x = 0; x < strlen(argv[1]); x++)
    {
        headNode->location[x] = argv[1][x];
        currentLocation[x] = argv[1][x];
    }

    headNode->location[x] = '\0';
    currentLocation[x] = '\0';
    headNode->next = NULL;

    currentNode = headNode;

    while(!finished)
    {
        finished = true;
        loopNode = headNode;
        currentLevel++;
        currentOrder = 1;
        while(loopNode != NULL)
        {
            if(!loopNode->isExpanded)
            {
                pDir = opendir (loopNode->location);
                for (x = 0; x < strlen(loopNode->location); x++)
                {
                    currentLocation[x] = loopNode->location[x];
                }
                currentLocation[x] = '\0';

                while ((pDirent = readdir(pDir)) != NULL) 
                {
                    finished = false;
                    if(!(!strcmp(pDirent->d_name, ".")||!strcmp(pDirent->d_name, "..")))
                    {
                        sprintf(temp, "%s/%s", currentLocation, pDirent->d_name);
                        addNode(temp);
                        currentOrder++;
                    }
                }
                closedir (pDir);
                loopNode->isExpanded = true;
            }
            loopNode = loopNode->next;
        }
    }

    currentNode = headNode;
    while (currentNode != NULL)
    {
        printf ("%d:%d:%s\n", currentNode->level, currentNode->order, currentNode->location);
        currentNode = currentNode->next;
    }

    return 0;
}



1 Answer: 

You're not checking that opendir's parameter is a directory, and trying to call it on files too. Either check opendir return value, or check that file you requesting to open is actually a directory, or - even better - both.

 

More Articles


linux - filter out content between two files

I have two files conditions.txtabcdefghlogs.txtefghijklmnopqrstI am expecting output to be:ijklmnopqrstActual output:efghijklijklmnopmnopqrstqrstHere's the code I had worked till nowfunc(){while read conditiondoif [[ $line = $condition ]] ; then:elseecho "$line";done < condition.txt}while read li

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

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


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

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

bash - attempting to recreate supervisor tutorial in docker, running into error (permissioning?)

I'm attempting to recreate the steps in this tutorial in a docker context, ubuntu image installed under coreos running in virtualbox on OS X.I've set up a Dockerfile that has the following steps:# Install docker basicsRUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/ap


linux - Dockerfile won't run script as user with sudo rights

I have this Docker file...FROM ubuntu:14.04 MAINTAINER Sindhu S sindhu@alum.hackerschool.org# RUN apt-get update && apt-get -y install sudo wget bash git && rm -rf /var/cache/apt-get/archives/*RUN adduser --disabled-password --gecos "" scrollback RUN adduser scrollback sudo RUN ech

ubuntu - Mysql won't start anymore

I wanted to check out my logserver again, but all of sudden i get this message when i visit the url:I am running on ubuntu xenialFATAL: Cannot connect to MySQL server on 'localhost'. Please make sure you have specified a valid MySQL database name in 'include/config.php'when i do journalctl -xe i get

python - What is the meaning of window size logarithm in zlib library?

The wbits argument controls the size of the history buffer (or the “window size”) used when compressing data, and whether a header and trailer is included in the output. It can take several ranges of values, defaulting to 15 (MAX_WBITS):" The wbits argument controls the size of the history buff

bash - Logstash in Docker - config file not found when mounted though a volume

EDIT: It seems to be a boot2docker thing... works fine in an ubuntu vm running docker.I'm trying to fire up logstash in a Docker container but when I mount the config file as a volume, it doesn't seem to find it. Interestingly, if I start up the container with bash, I can see the config file in ther