PlayHardGoPro
PlayHardGoPro

Reputation: 2933

Pointer of a struct with vector - Segmentation Fault

Why can't I assign a value to qtd_lines ?

typedef struct{
  int x;
  int y;
  char z;
}struct_c;

typedef struct{
   int qtd_lines;
   struct_c *vector;
}struct_a;

int main(){
 struct_a *pointer;

//This gives me Segmentation Fault.
 pointer->qtd_lines = 10;
 pointer->vetor = (struct_c *)  malloc(pointer->qtd_lines * sizeof(struct_contas));

 return 0;
}

Ok, I have a vector in my struct_c, but the field qtd_lines is not a vector, right ? So Why am I getting this error ?

Upvotes: 0

Views: 191

Answers (3)

user5233990
user5233990

Reputation:

In your case only structure pointer is declared. No memory is allocated for that.

Assign this like so:

struct_a* pointer = (struct_a*)malloc(sizeof(struct_a));

Also once you done your things please don't forget to free that memory since it was taken from the Heap memory segment.

free(pointer);

Hope it helps.

Upvotes: 0

flogram_dev
flogram_dev

Reputation: 42858

Pointers store memory addresses only.

struct_a *pointer;

This just declares a variable that holds some memory address. At that memory address there might be a struct_a object, or there might not be.

Then how do you know whether pointer points to an actual object or not? You have to assign a memory address to the pointer.


You can either dynamically allocate a block of memory to hold the object, and assign the address of that memory to pointer:

pointer = malloc(sizeof(struct_a));

Or you can allocate the object on the stack, and then store the memory address of that object in the pointer:

struct_a foo;
pointer = &foo;

But as it stands, in your code pointer doesn't point to anything, but you use the -> operator to access the memory that the pointer points to.

And in C you actually can do that, but you get undefined behavior. Like a segmentation fault. Or possibly just weird behavior. Anything is possible.

So, just make the pointer point to something before using it.

Upvotes: 2

haccks
haccks

Reputation: 106092

pointer->qtd_lines = 10; is writing at unallocated location. You need to initialize pointer.

 struct_a *pointer = malloc(struct_a);

Upvotes: 1

Related Questions