Quantcast
Channel: DaniWeb Solved Topics
Viewing all articles
Browse latest Browse all 564

Creating a structure in function gives gegmentation fault [C]

$
0
0

Hi, I'm writing in C my program and I have a problem with this pieces of code:

//lib.h
typedef struct Array {
    char **array;
    char *searchDirPath;
    char *searchFile;
    char *tmpFileName;
    int tmpFile;
    int arraySize;
    int currIndex;
} Array;

// lib.c

Array* createArray(int size) {
    Array* newArray = calloc(1,sizeof(Array));
    newArray->array = calloc((size_t)size,sizeof(char*));

    newArray->arraySize = size;
    newArray->currIndex = 0;
    char fileName[] = "tmpXXXXXX";
   newArray->tmpFile = mkstemp(fileName);
    newArray->tmpFileName = fileName;

   showYourself(newArray);
    return newArray;
}

void showYourself(Array* a) {
    printf("\n\n==========================================\n");
    printf("\nShowing myself:\n arraysize:  ");
    printf(sizeof(a->array));
    printf("\nSearch directory path:  ");
   printf(a->searchDirPath);
    printf("\nSearch file path:  ");
    printf(a->searchFile);
    printf("\nTmp file:  ");
   printf(a->tmpFileName);
    printf("\nArray size:  ");
    printf("%d",a->arraySize);
    printf("\nCurrent index:  ");
    printf("%d",a->currIndex);
    printf("\n==========================================\n\n");
}

// main.c
#include "stdio.h"
#include "lib.h"

int main() {
    printf("Hello world\n");
    sayHello();

    Array*a = createArray(8);
   showYourself(a);
    setDir(a, "/home/kamil/gsl-2.5");
    setSearchFile(a, "borosh13.c");    // /home/kamil/gsl-2.5/rng/borosh13.c
     showYourself(a);
    search(a);

    return 0;
}

This is only a sample, but I havent tested other part yet. In the short: it gives segmentation fault.
I think if comes from printf(sizeof(a->array)); (when I comment this line program works to the end), so I probably missed something in createArray function but can't see a problem. I would be very grateful if you could take a look and check if there is a bug.


Viewing all articles
Browse latest Browse all 564

Trending Articles