iCas iCas - 1 year ago 38
C Question

Why use the malloc?

I was trying to make a code to find duplicates in an array and print them. I can't understand this code and why the malloc is being used and the int main part isn't clear to me.

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

void printRepeating(int arr[], int size)
{
int *count = (int *)calloc(sizeof(int), (size - 2));
int i;

printf(" Repeating elements are ");
for(i = 0; i < size; i++)
{
if(count[arr[i]] == 1)
printf(" %d ", arr[i]);
else
count[arr[i]]++;
}
}

int main()
{
int arr[] = {4, 2, 4, 5, 2, 3, 1};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printRepeating(arr, arr_size);
getchar();
return 0;
}

Answer Source

This code is really wrong, you shouldn't use it at all.

To give you some hints, this line creates an array:

int *count = (int *)calloc(sizeof(int), (size - 2));

Similar to:

int count[size - 2] // If size was a constant

An unfortunate issue is that the function never disposes the dynamically created array, so you'll see a memory leak.

Line count[arr[i]]++ is a disaster: if the value of arr[i] is greater than size-2 then the software will write to an unassigned memory.

To show how it should be done:

// No value should exceed 50
#define MAX_ARR 50

void printRepeating(int arr[], int size)
{
    int found[MAX_ARR];
    int i;

    // Set found variable to 0
    memset(found, 0, sizeof(found));

    for(i = 0; i < size; i++)
    {  
        // Did we find the same number before?
        if (found[arr[i]] == 1) {
            // Yes, print it
            printf(" %d ", arr[i]);
        } else {
            // No, mark is as found
            found[arr[i]] = 1;
        }
    }   
} 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download