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.

Ok, I get it, I can't just use printf. ..., I lost an hour with this problem looking for a bad allocated table and here we are. Thanks for all who wantd to help

Member Avatar for kevenm

I see trouble with lines 20 and 22. And a comment on 31.

Line 31. printf (sizeof(a->array))
hmm, Where is the format?
I would think you wanted

printf ("%d\n", sizeof(a->array));

But then, of course, you should always get the value 8 or 4,
whatever sizeof(char*) is. array is just a pointer, not an array itself.

Line 20 filename is declared here as a local variable to the function.

Line 22, you assign it to the pointer tmpFileName.
When you return from this function, the variable filename does not exists,
and its address would be invalid (begin some place on the stack).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.