4

C question

Hi,

I am passing a double pointer to a function to allocate a double array and initialise the array inside the function with lets say 10.10;

I do the following but get segmentation fault when I access the array in main;

void function(double **array, int size){

    *array = (double*) malloc(size * sizeof(double)); 
    int i;
    for(i=0;i<size;i++){
    *array[i] = 10.10;
    }


}

int main(){

    double *array = NULL;

    function(&array,20);
    printf("array[0] = %lg\n",array[0]);// here is where I get segmentation fault


}

Any help ?

5
  • 1
    "here is where I get segmentation fault" is not on the line where you get the segfault. Commented Jan 18, 2013 at 14:48
  • as a sidenote: the cast to double* is a) unnecessary, and b) wrong, because what you really have there is double** Commented Jan 18, 2013 at 14:49
  • 2
    @Andreas: you're right about (a) but not (b) ;-) Commented Jan 18, 2013 at 14:50
  • @AndreasGrapentin It's rather wrong because it's unsafe. Commented Jan 18, 2013 at 14:53
  • @PaulR whoops, you're right of course. Commented Jan 18, 2013 at 15:13

2 Answers 2

4

You have fallen foul of operator precedence.

Change:

for(i=0;i<size;i++){
    *array[i] = 10.10;
}

to:

for(i=0;i<size;i++){
    (*array)[i] = 10.10;
}

Note that if you had compiled with warnings enabled (e.g. gcc -Wall ...) your compiler would have caught this for you. Always compile with warnings enabled and always pay heed to, understand and fix any warnings.

Sign up to request clarification or add additional context in comments.

Comments

2
*array[i]

doesn't mean what you think it does (look it up using a C operator precedence table).

Instead of unreadable, ugly and confusing (yes, it just confused you) code, use a temporary variable (and do not for the love of God cast the return value of malloc!):

void function(double **array, int size)
{
    if (array == NULL) return;

    double *tmp = malloc(size * sizeof(*tmp)); 
    if (tmp == NULL) {
        *array = NULL;
        return;
    }

    int i;
    for (i = 0; i < size; i++) {
        tmp[i] = 10.10;
    }

    *array = tmp;
}

Also, return 0; from main(). Really.

4 Comments

Perhaps a *array = NULL in the event of malloc failure would not go amiss.
@EdHeal And a check for the address of the output argument being valid (non-NULL) as well :)
return 0 from main() is good style, but not necessary since C99.
@Lundin I didn't suggest it because it was necessary, but because it's good practice, as you suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.