简体   繁体   中英

Run Time Error in Hacker Rank problem : 1D Arrays in C

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 (ie 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.

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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM