I am setting a pointer to pointers like in the code above. The problem is that malloc is throwing a segmentation fault no matter what I have tried. Here is the code:
wchar_t **Words ;
int lc = lineCounter() ;
**Words = malloc( lc * sizeof(int) ) ;
if (**Words == NULL) return -1 ;
The lineCounter function is just a function that returns the number of lines in a file. So what I try to do is free some memory that is needed to save the pointers to lc number of words.
Here is a visual representation of what I have in mind :
Let me explain your code line by line:
wchar_t **Words ;
It is creating a pointer pointing to a pointer on wchar_t. The thing is, at creation it is pointing on a random area in the memory so it may not be yours.
*Words = malloc( lc * sizeof(int) ) ;
This line dereferences the pointer and modify it's content. You're trying to modify a memory area that doesn't belong to you.
I think that what you want to do is:
wchar_t **Words ;
int lc = lineCounter() ;
Words = malloc( lc * sizeof(wchar_t *) ) ;
if (Words == NULL) return -1 ;
And then malloc all the dimensions in your array.
EDIT:
You may want to do something like that to correspond to your scheme:
wchar_t **Words ;
int i = 0;
int lc = lineCounter() ;
Words = malloc( lc * sizeof(wchar_t *) ) ;
if (Words == NULL) return -1 ;
while (i < lc)
{
Words[i] = malloc(size_of_a_line * sizeof(wchar_t));
if (words[i] == NULL) return -1;
++i;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With