Question

my C program compiles and runs fine in PuTTY until repeating the loop for the second time. A friend with the same code seemed to be able to get his program to work, and I even tried changing any differences between my code and his to his code, and still no cigar. Listed below is the code and an example of what happens when the code is executed. I believe the issue lies within the malloc statement.

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


void getInts(int ** integersArray, int * numInput);

int main() {

  int * integersArray;
  int numInput;
  int i;

  getInts(&integersArray, &numInput);

  for (i = 0; i < numInput; i++) {
    printf("number %d = %d\n", i+1, integersArray[i]);
  }

  return 0;
}


void getInts(int ** integersArray, int * numInput) {
  int i;

  printf("Please enter the number of intergers you want to input\n");
  scanf("%d", numInput);

  *integersArray = (int *) malloc(sizeof(int) * *numInput);

  for (i = 0; i < *numInput; i++) {
    printf("please enter integer %d: ", i+1);
    scanf("%d", (integersArray[i]));
  }
}

Output

Please enter the number of intergers you want to input
4
please enter integer 1: 2
please enter integer 2: 3
Segmentation fault (core dumped)
Was it helpful?

Solution

The problem is here:

scanf("%d", (integersArray[i]));

Remember, integersArray is a pointer to the array. In other words, it is a pointer to a pointer to the first element in the array.

Instead try:

scanf("%d", &(*integersArray)[i]);

First, since integersArray is a pointer to the int array, I dereference it: (*integersArray).

Then, I index to the ith element in the array: (*integersArray)[i].

But, scanf expects the address of the integer which gets the result, I take the address of that element: &(*integersArray)[i].

The important thing to remember is that you must dereference integersArray first.

Confirmed with gcc 4.8.2 i686-pc-cygwin.


Here's what should be happening, and indeed happens (by luck!) on the first iteration.

                                             ______
integersArray ---> <malloc_result>  --->    |______|
                                            |______|
                                            |______|
                                            |______|

However, on the second iteration, the wrong pointer is being indexed, like this:

                                             ______                                            
integersArray -|   <malloc_result>  --->    |______|
               |                            |______|
               |                            |______|
               |                            |______|
               |    
               |-> <malloc_result+4>  --->    ?????????
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top