1

I wrote this simple code to test a bigger implementation I have and I get trash values plus a seg fault. One solution is to declare int* a and int* b as global and take out the arguments of fill. My question is, what is the consideration of memory handling in both cases, and why does it throw an error?

#include <stdio.h>
#include<stdlib.h>
#define LENGTH 4

void fill(int* a, int* b){
  a = (int*) malloc(LENGTH * sizeof(int));
  b = (int*) malloc(LENGTH * sizeof(int));

  for(int i=0; i< LENGTH;i++){
    a[i]=i;
    b[i]=i+10;
  }
 }

void printArray(int* a, int* b){
   for(int i = 0 ; i < LENGTH; i++)
    printf("%d\n",a[i] );

  for(int i = 0 ; i < LENGTH; i++)
    printf("%d\n",b[i] );
}

int main(){

    int* a;
    int* b;

    fill(a,b);
    printArray(a,b);

}
Paul R
  • 208,748
  • 37
  • 389
  • 560
Pash
  • 23
  • 3
  • 2
    The line `fill(a,b);` generates two compiler warnings: *uninitialized local variable used*. The values set in the function do not find their way back to the variables in `main` so they are still uninitialised in `printArray(a,b);` – Weather Vane Jan 23 '19 at 10:44
  • 1
    You're passing your pointers by value - you need to add another level of indirection so that you can pass them by reference. Alternatively do the allocation/freeing in main and keep the functions as they are. – Paul R Jan 23 '19 at 10:45
  • 1
    You should pass the address of the pointers: `fill(&a, &b);` and then make necessary changes to the function – Spikatrix Jan 23 '19 at 10:45

2 Answers2

2

You should pass pointers to pointers as arguments to the fill function so you can effectively modify the pointers a and b.

void fill(int** a, int** b){
    *a = malloc(LENGTH * sizeof(int));
    (*a)[i]=i;

fill(&a,&b);
Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
0

Whenever you send args to a function in c they are always sent by value. here, you send by value the addresses that a and b point to - they are uninitialized- so junk values.

When you use malloc- it returns a pointer to an address on the heap. in your function the local values of a and b change. but in your main function they do not. if you want your function to change the address the pointers are pointing to in outside of the function you must send **a and **b. now when you change the address for a : * a= malloc() you change the value the pointer is holding. So now your a and b pointers will hold the new addresses allocated.

void fill(int** a, int** b)/*here you send by value the pointers addrsses */
{
 int* aptr = NULL;
 int* bptr = NULL;


 *a = (int*) malloc(LENGTH * sizeof(int));/*update the value pointe a is pointing to */
 *b = (int*) malloc(LENGTH * sizeof(int));

 aptr = *a;
 bptr = *b;

 for(int i=0; i< LENGTH;i++){
  aptr[i]=i;
  bptr[i]=i+10;
 }
}
H.cohen
  • 517
  • 3
  • 9