cpointersdynamic-memory-allocation

Segfault with memcpy and array


I'm learning C and just ironing out my understanding of how memory is allocated. I'm playing around with the following code and it's segfaulting but I'm not sure why. Any pointers? (no pun intended)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Table {
  int* elements;
} Table;

int main(void) {
  Table* table = {0};
  table->elements = calloc(1, sizeof(int)*3);
  memcpy(table->elements, (int[]) {1, 1, 1}, 3*sizeof(int));

  int* new_elements = calloc(1, sizeof(int)*5);
  memcpy(new_elements, (int[]) {2, 2, 2, 2, 2}, 5*sizeof(int));

  free(table->elements);
  table->elements = new_elements;

  for (int i = 0; i < 5; i++) {
    printf("%d\n", table->elements[i]);
  }

  return 0;
}

Solution

  • Table* table = {0}; initializes table to a null pointer. It points to “nothing.”

    Then table->elements = … attempts to use table to refer to the elements member in a structure. But, since table points to nothing, there is no structure and no member to access. Most likely, this results in attempting to access memory that is not mapped for your process and causes a segment fault.

    To fix it, you must set table to point to memory for a structure of type Table. Or you could change table to be a structure rather than a pointer and make corresponding changes in the code, such as changing table->elements to table.elements.