billpcs
billpcs

Reputation: 633

malloc causes segmentation fault in C

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

Upvotes: 4

Views: 4247

Answers (2)

Mantoine
Mantoine

Reputation: 642

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;
}

Upvotes: 8

Eric Lippert
Eric Lippert

Reputation: 660533

A pointer refers to a storage location. A variable is an example of a storage location.

The * operator takes a pointer and gives you the storage location that the pointer refers to.

words is a pointer; it refers to a storage location of type pointer to wchar_t. Since it is not initialized, it is undefined what storage location it refers to.

Applying the * operator takes the pointer and produces the location it refers to; since you haven't said what location it refers to, writing to that location could do anything, including crash.

You need to make the pointer words refer to a location before you assign something to *words.

Upvotes: 3

Related Questions