Saher Ahwal
Saher Ahwal

Reputation: 9237

Segmentation Fault - declare and init array in C

I am very new to C. coming from Python, Java and C# worlds. This might be a stupid question but I am getting segmentation fault:

// struct for storing matrices
typedef struct {
    int m;
    int n;   
    float* elts;
} Matrix;

and in my main method:

 Matrix A;
    A.n = 3;
    A.m = 3;
    memcpy( A.elts, (float[]) {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f}, 9 * sizeof(float));  // seg fault because of this memcpy.

I also tried without the f, same issue. Can you help please

Upvotes: 0

Views: 385

Answers (3)

z242
z242

Reputation: 435

You have not allocated any memory to hold the float values. Prior to the memcpy you need something like:

A.elts = malloc(9* sizeof(float));

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

In C arrays and pointers are related, but they are not the same. It is not enough to declare a pointer in order to make it an array: you need to set that pointer to a value pointing to a block of memory of sufficient size.

To make your example work, add

A.elts = malloc(sizeof(float) * 9);

before calling memcpy. Otherwise, the pointer elts remains uninitialized, so writing to memory pointed by that pointer is undefined behavior. Note that you would need to call free(A.elts) when you are done with the array.

Another alternative would be declaring elts as a fixed-size array, not as a pointer:

float elts[9];

This would not allow resizing the array, though.

Upvotes: 3

rjp
rjp

Reputation: 1820

You need to allocate memory for A.elts to point to. You can do this with malloc. What you are doing is coping the constant array you specified into whatever address elts happens to point to (it is uninitialized).

You can also point A.elts to the constant array like so:

float *myFloats = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
A.elts = myFloats;

Upvotes: 2

Related Questions