Search code examples
cintdereference

Cannot assign int to dereferenced int in C


I am lost. I cannot assign an int to a dereferenced int *.

  printf("in octave\n");

  int *default_octave;
  printf("attr[%d]: %s\n",i+1,attr[i+1]);

  const char *octave_char = attr[i+1];
  printf("octave_char: %s\n", octave_char);

  int octave_number = atoi(octave_char);
  printf("octave_number: %d\n", octave_number);
  fflush(stdout);

  *default_octave=octave_number;
  printf("in octave pt 2\n");
  fflush(stdout);

This is the output:

in octave
attr[1]: 4
octave_char: 4
octave_number: 4
Segmentation fault

Why?

Running the GDB debugger gets to that line and then seg faults, too.

4

0            int octave_number = atoi(octave_char);
(gdb) s
41            printf("octave_number: %d\n", octave_number);
(gdb)
octave_number: 4
42            fflush(stdout);
(gdb)
43            *default_octave=octave_number;
(gdb) print octave_number
$1 = 4
(gdb) s

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400a7b in parse_song (song_data=0x7fffffffe7a8, attr=0x602600) at nullaby.c:43
43            *default_octave=octave_number;
(gdb)

I have no idea what I can do to fix this.


Solution

  • You have an int pointer. Right.

    It just mean you have a variable pointing to some memory area.
    But you haven't allocated/reserved that memory area. So it can point to anything.

    And it will surely point to a memory area you don't own, hence the segmentation fault.

    You need to allocate memory for the pointer...

    For instance:

     int * default_octave = malloc( sizeof( int ) );
    

    Or you may also use:

    int   default_octave_val;
    int * default_octave = &default_octave_val;
    

    Either you allocate memory to store your int (and then get a pointer to a valid memory area), or you create a pointer to an existing memory area (in the given example, a stack address).

    Then you can de-reference that pointer, as it points to a valid memory area.
    If it don't, you'll have a segmentation fault, or a bus error, depending on your OS.