LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   C: what's the right structure to hold a (previously unkown sized) file in memory? (http://www.linuxquestions.org/questions/programming-9/c-whats-the-right-structure-to-hold-a-previously-unkown-sized-file-in-memory-4175419387/)

eantoranz 07-30-2012 10:47 AM

C: what's the right structure to hold a (previously unkown sized) file in memory?
 
Hi!

I have to read an mcrypt-encrypted file from FS and I want to keep it in memory.

The thing is that I don't know before-hand the size of the file so I don't know the size of the char * I will have to use to hold its content.

So, the structure I'm using to hold the file content is called file_content. Given that I will have to dynamically allocate the char* content I will use a char**, right?

So:

Code:

char ** file_content;
I allocate it with this:

Code:

file_content = malloc(sizeof(char) * st.st_size);
st.st_size being the size of the file from stat.h. Now, when I start reading the file I should start setting each of the chars in *file_content, right?

So:
Code:

i = 0;
char aChar;
while (i < st.st_size && fread(&aChar, 1, 1, mcrypt_input) == 1 ) {
    mdecrypt_generic (td, &aChar, 1);
    *file_content[i] = aChar;
    i++;
}

Ain't that right? Well, I know it ain't right cause I'm getting a seg-fault. So what am I missing?

Thanks in advance.

eantoranz 07-30-2012 11:03 AM

By the way, segfault is here:

Code:

*file_content[i] = aChar;

eantoranz 07-30-2012 11:18 AM

Well.... I changed file_content to char* and now it works (with the corresponding changes in the rest of the code).


All times are GMT -5. The time now is 06:54 PM.