Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc causes segmentation fault in C

Tags:

c

pointers

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 :

enter image description here

like image 811
billpcs Avatar asked Dec 19 '22 14:12

billpcs


1 Answers

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;
}
like image 120
Michel Antoine Avatar answered Jan 03 '23 21:01

Michel Antoine