0

I am trying to solve the 1D Arrays in C problem on Hacker Rank: here

We have to print the sum of the integers in the array.

My code:

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

int main() 
{
    int n;
    int sum = 0;
    int *a = malloc(n * sizeof(int));
    scanf("%d", &n);
    getchar();
    for (int i = 0; i < n; i++)
    {
       scanf("%d ", &a[i]);
       sum += a[i];
    }
    printf("%d", sum);
    free(a);   
    return 0;
}

But the compiler gives error for some select test cases. The compiler message (error):

Compiler Message:
Abort Called

Error (stderr):
1.corrupted size vs. prev_size
2.Reading symbols from Solution...done.
3.[New LWP 129788]
4.[Thread debugging using libthread_db enabled]
5.Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
6.Core was generated by `./Solution'.
7.Program terminated with signal SIGABRT, Aborted.
8.#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50

Some observations:

  1. This program is running properly in VS Code.
  2. Custom inputs (i.e. Custom test cases) given by me compiles successfully (using the "Test against custom input" feature of Hacker Rank).
  3. But it is only some select test cases which are giving this error.

Kindly point out the possible error in my code which is causing this problem.

James Z
  • 12,209
  • 10
  • 24
  • 44
Ultimate
  • 25
  • 2
  • 8

1 Answers1

0

Specify the size of an array before initializing the memory space dynamically. How can you initialize the space before entering the size of an array?

And you have to specify cast type when you allocate the memory dynamically.

here: a = (cast_type *) malloc (byte_size);

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

int main(){
           int n; 
           int sum=0; 

           printf("Enter size of the array:\n");
           scanf("%d", &n);

           int *a = (int*)malloc(n * sizeof(int));

           for (int i = 0; i < n; i++) {
                scanf(" %d", &a[i]);
           }

           for (int i = 0; i < n; i++) {
                sum += a[i];
           }
           printf("Sum of array elements is: %d\n", sum);
           free(a); 
           return 0;
        }
  • Type casting during memory allocation is quite controversial . Some of the users on this website cautioned me against doing it . For your reference :[Link](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Ultimate Jan 21 '22 at 05:49
  • malloc returns void*, a is int*. This is a type mismatch. The cast resolves that. But as you said it is right, in c it is not required to type cast, but in c++ it is required. And everywhere in the syntax cast type is written before malloc weather it's c or c++. – Aditya Anand Jan 21 '22 at 07:11