Memory allocation problem

Hello. Trying to allocate some memory inside a function and then use it outside of the function. For some reason it doesn't work. This is my code:

http://hastebin.com/otosirafup.mel

edit: forgot to say, it crashes with seg fault on the printf
Last edited on
Please add that you want a C- not a C++-solution in your question...

maybe the array size is 0 and you don't allocate memory at all.
Additionally please give us the content of the file (or at least what's necessary) so we can reproduce the error
Last edited on
You must declare the size of the struct inside the main function and use it as argument for the function, or use the void function to display the size of the words and you will not need to declare the struct inside the main and use it as argument, you will do it inside de void.

int main(){
Words *words = malloc(SIZE*(sizeof(Words)));
storeFileWords("ordlista.txt", words);
printf("%d", words[0].size);
return 0;
}
After looking at it again...

changing a pointer in a function won't change the pointer itself.
This may be confusing but see the example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int a = 6;
int b = 10;

void change(int* value) {
    value = &b;  // changes local copy
}

int main() {
    int* v = &a; // points at a
    change(v);
    printf("%d", *v); // prints 6
    return 0;
}


in your example, try passing Words** words to storeFileWords
don't forget that you have to dereference the pointer in storeFileWords

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void storeFileWords(char* filename, Words** words){ 
    // ...
    
    words = (Words*)malloc(arraySize*sizeof(Words));
    *words = (Words*)malloc(arraySize*sizeof(Words));

    words[0].size = arraySize;
    (*words)[0].size = arraySize; // and everything alike

    // ...
 }

int main(){
Words *words;
storeFileWords("ordlista.txt", &words);
printf("%d", words[0].size);
return 0;
} 
Topic archived. No new replies allowed.