Home > Mobile >  Why is this malfunctioning?
Why is this malfunctioning?

Time:03-21

I have this program in C:

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

typedef struct sl{
  int32_t length;
  int32_t* arr;
} Selector;

void somefunction(Selector* temp){
  temp->length = 10;
  temp->arr = (int32_t*)malloc(temp->length * sizeof(int32_t));

  for(int i=0; i<temp->length; i  ){
    temp->arr[i] = i*i;
  }
}

int main () {
  Selector* sel;

  // Make changes to struct from other function
  somefunction(sel);

  // Print each element
  for(int i=0; i<sel->length; i  ){
    printf("Content of index %d: %d\n",i,sel->arr[i]);
  }
  printf("\n");

  return(0);
}

I run it in PowerShell with: gcc .\stest.c; .\a.exe, and it works fine:

Content of index 0: 0
Content of index 1: 1
Content of index 2: 4
Content of index 3: 9
Content of index 4: 16
Content of index 5: 25
Content of index 6: 36
Content of index 7: 49
Content of index 8: 64
Content of index 9: 81

But if I change int main() to this:

int main () {
  Selector* sel;

  // Make changes to struct from other function
  somefunction(sel);

  // Print each element
  for(int i=0; i<sel->length; i  ){
    printf("Content of index %d: %d\n",i,sel->arr[i]);
  }
  printf("\n");

  // ============= ADDED CODE BELOW ============= //
  // Change each element a bit
  for(int i=0; i<sel->length; i  ){
    sel->arr[i] = sel->arr[i]   10;
  }

  // Print each element again
  for(int i=0; i<sel->length; i  ){
    printf("Content of index %d after change: %d\n",i,sel->arr[i]);
  }
  printf("\n");
  // ============= ADDED CODE ABOVE ============= //
  return(0);
}

Suddenly it just gets a segmentation fault? Why? I didn't use the stack and overload it, I used malloc for the small arrays, it's not passing around references again like into the function to make memory go missing or something. Why doesn't this work? And how am I supposed to do it otherwise?

CodePudding user response:

Credit goes to the guys in the comments who gave the solution.

The problem was caused by undefined behavior, because the pointer was not set to anything.

  int main() {

  Selector sel;

  // Make changes to struct from other function
  somefunction(&sel);

  // Print each element
  for(int i=0; i<sel.length; i  ){
    printf("Content of index %d: %d\n",i,sel.arr[i]);
  }
  printf("\n");

  // ============= ADDED CODE BELOW ============= //
  // Change each element a bit
  for(int i=0; i<sel.length; i  ){
    sel.arr[i] = sel.arr[i]   10;
  }

  // Print each element again
  for(int i=0; i<sel.length; i  ){
    printf("Content of index %d after change: %d\n",i,sel.arr[i]);
  }
  printf("\n");
  // ============= ADDED CODE ABOVE ============= //
  return(0);
}

To summarize it, for posterity and others running into the same problem:

  • Don't make "sel" a pointer.
  • Send "sel" as a reference.
  • Change member-variable access accordingly.
  • Related