Search code examples
javacprogramming-languages

Difference between C and JAVA program


I have two examples of the same program. This program has a function which creates an array and returns the pointer to array.

First program (in C):

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

#define N 5

int* GetValues()
{
   int items[N] = { 1, 2, 3, 4, 5 };
   return items;
}

int main(int argc, char** argv) {

    int *array = GetValues();    
    int i;    
    for(i = 0; i < N; i++)
    {
        printf("%d\n", array[i]);
    }    

    return (EXIT_SUCCESS);
}

Second program (in Java):

package tests;

public class Tests {

    public static int[] foo() {        
        int array[] = { 1, 2, 3, 4, 5 };
        return array;        
    }

    public static void main(String[] args) {        
        int[] array = foo();        
        for(int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }                
    }
}

The result of the Java program is the following: 1, 2, 3, 4, 5

The result of the C program is the following: 1 -1075386156 -1218492432 1 -1216747208

Why do we have that different results? My version is the following.

In C program inside of the GetValues() function the items[] local array will be created and initialized. The return instraction will return the pointer to begining of the array, but this array will be allocated at the LOCAL memory of that function. When the last instruction of the GetValues() function will be invoked the local memory will be destroyed. In this case we can't predict what data are stored there and we dont know what will print the printf("%d\n", array[i]) instruction (no wonder, the memory has been destroyed and values as well).

In java program we have the following situation. Arrays in JAVA are objects. Objects in java are storing in heap. So, after executing foo() method the object array will be created and puted to the heap. After executing method local variables will be cleaned, but our pointer to array-object is still in the heap (garbage collector will understand when this object has to be deleted), what is why we are able to print it normally.

Am I right? Do I understand this features properly? If not can somebody correct me? Thanks in advance.

P.S. Sorry for my english I hope I explained my problem more or less clear.


Solution

  • Yes, you are entierly correct. The array in Java is stored on the heap and is returned to the caller. The java program is just as you wrote:

    int array[] = new int[5];
    array[0] = 1;
    ...etc.
     return array;  
    

    Which is no problem.

    The array in the C program is local to the function, and the pointer to those local values are invalid when that function returrns.