The monitored command dumped core? - c

Well on a regular basis i get obstructed with this error , the monitored command dumped core.
Which is pretty much alien language to me, hence i cannot not possibly understand what the compiler is saying.
I looked up the internet , for what could be the reason and found out that i could be accessing index which has not been allocated memory, therefore i set on to make a simplest code possible and encounter the same error.
#include<stdio.h>
int main()
{
int n;
int a[100000];
scanf("%d",&n);
int j=0;
for(int i=2;i<=n;i+2)
{
if (i%2==0)
{
a[j]=i;
j+=1;
}
}
return 0;
}
But i don't understand how i could be accessing non allocated memory.
Also what could be the other reasons for the same error to occur such frequently.

I think the issue could be your for loop, as in the third part you're not updating i. To update, write it as i=i+2 or i+=2.

Your index j gets out of bounds:
Demonstration:
#include<stdio.h>
int main()
{
int n;
int a[100000];
scanf("%d", &n);
int j = 0;
for (int i = 2; i <= n; i + 2)
{
if (i % 2 == 0)
{
if (j > 100000) // <<<<<<<<<<<<<<
{
printf("Bummer\n");
return 1;
}
a[j] = i;
j += 1;
}
}
return 0;
}
Accessing an array with out of bounds results undefined behaviour (google that term).

You are incrementing the value of i. You have written i+2 instead of i+=2.
#include<stdio.h>
int main()
{
int n;
int a[100000];
scanf("%d",&n);
int j=0;
for(int i=2;i<=n;i+=2)
{
if (i%2==0)
{
a[j]=i;
j+=1;
}
}
return 0;
}

You are writing i+2 ,but you have to write i+=2.

Related

The count of duplicate elements is double what it should be

I am working on an old exam and the problems states that a given array (int zahlen[]={1,4,5,1,5,7,9,2,3,4}) has values that are the same. The task is to replace the values that are the same with '-1'. After each replacement, a given variable, count, has to be increased by one.
My problem is that the variable count is two-times higher than normal (In this case there are only 3 of the same numbers and the variable shows 6.)
The function is called array_unique. I am would be grateful for a brief explanation of my mistake.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("chcp 1252");
int zahlen[]={1,4,5,1,5,7,9,2,3,4};
int len = sizeof(zahlen)/sizeof(int);
int erg = array_unique(zahlen,len);
printf("Es wurden %d doppelte Zahlen gelöscht: \n",erg);
printf("Das Array hat nun folgende Werte: ");
printArrayUnique(zahlen,len);
return 0;
}
void printArrayUnique(int *array, int len){
for(int i=0; i<len; i++){
if(array[i]!=-1){
printf("%d ",array[i]);
}
}
}
int array_unique(int *array, int len){
int count=0;
for(int i=0; i<len;i++){
for(int j=i+1; j<len;j++){
if(array[i]==array[j]){
array[j] = -1;
count++;
}
}
}
return count;
}
I have not figured out any other solution to fix the faulty value of count.
The issue is due to the fact that your are counting duplicates more than once; so, when you have found a duplicate entry, you correctly replace that with -1 but then, later in the loops, you will be (potentially, at least) comparing two or more of those -1 values.
Just add a check that either value is not -1 (along with the test for equality) before incrementing the count variable:
int array_unique(int* array, int len)
{
int count = 0;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (array[i] == array[j] && array[j] != -1) {
array[j] = -1;
count++;
}
}
}
return count;
}
Note also that, as mentioned in the comments, you really do need declarations of your functions before you use them. Add the following two lines before the main function:
void printArrayUnique(int* array, int len);
int array_unique(int* array, int len);

why am i getting segmentation error on hackerearth for a sorting question

i was getting segmentation error on hacker earth with this code.
I know its a invalid memory reference error, but I can't seem to find the cause of the error in my code.
here is my code
#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>
int* awseomeSort (int N, int* arr) {
// Write down your code
int awesome_sort[N];
int odd_arr[N],even_arr[N],o=0,e=0;
for(int i=0;i<N;i++){
if(arr[i]%2==0){
even_arr[e]=arr[i];
e++;
}
else {odd_arr[o]=arr[i];
o++;}
}
int sorted_even[e];
int k=0;
for(int i=0;i<e;i++){
for(int j=0;j<e;j++){
if(even_arr[j]%5==0){
if(even_arr[j]>even_arr[i]){
sorted_even[k]=even_arr[j];
k++;
}
else if(even_arr[i]%5==0){
sorted_even[k]=even_arr[i];
k++;}
}
else {if(even_arr[i]%5==0){
sorted_even[k]=even_arr[i];
k++;
} else if(j>i){
sorted_even[k]=even_arr[j];
k++;
} else {
sorted_even[k]=even_arr[i];
k++;
}
}
}
}
for(int i=0;i<N;i++){
if(i<k){
awesome_sort[i]=sorted_even[i];
}
else {int m=0;
awesome_sort[i]=odd_arr[m];
m++;
}}
return awesome_sort;
}
int main() {
int out_n;
int T;
scanf("%d", &T);
for(int t_i = 0; t_i < T; t_i++)
{
int N;
scanf("%d", &N);
int i_arr;
int *arr = (int *)malloc(sizeof(int)*(N));
for(i_arr = 0; i_arr < N; i_arr++)
scanf("%d", &arr[i_arr]);
int* out_ = awseomeSort(N, arr);
printf("%d", out_[0]);
for(int i_out_ = 1; i_out_ < N; i_out_++)
printf(" %d", out_[i_out_]);
printf("\n");
}
}
please help me with the wrongs or mistakes i'm making here
ignore below:
Maybe you're right, I changed all the array sizes to '100000', but now I'm getting time limit exceeded.But I have two questions: 1. Why do you specifically state the value upto '100000' ? Shouldn't it be like '32767' ? 2. Is there something else I could do to get around this problem ? Because my code looks too simplistic when I compared it to other submissions which had used a lot of complicated functions and methods which I am unaware of as of now. Mine works totally fine and gives the right output.

How to read space-separated integers representing the array's elements and sum them up in C

How to read space-separated integers representing the array's elements and sum them up in C?
I used the below code but it reads all the elements in a new line:
#include <math.h>
#include <stdio.h>
int main() {
int i = 0, N, sum = 0, ar[i];
scanf("%d" , &N);
for (i = 0; i < N; i++) {
scanf("%d", &ar[i]);
}
for (i = 0; i < N; i++) {
sum = sum + ar[i];
}
printf("%d\n", sum);
return 0;
}
Your array ar is defined with a size of 0: the code invokes undefined behavior if the user enters a non zero number for the number of items.
Furthermore, you should check the return value of scanf(): if the user enters something not recognized as a number, your program will invoke undefined behavior instead of failing gracefully.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int i, N, sum;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
int ar[N];
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
return 0;
}
Note that the program will still fail for a sufficiently large value of N as there is no standard way to check if you are allocating too much data with automatic storage. It will invoke undefined behavior (aka stack overflow).
You should allocate the array with malloc() to avoid this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, N, sum;
int *ar;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
ar = malloc(sizeof(*ar) * N);
if (ar == NULL) {
fprintf(stderr, "cannot allocate array for %d items\n", N);
return 1;
}
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
free(ar);
return 0;
}
Finally, there is still a possibility for undefined behavior if the sum of the numbers exceeds the range of type int. Very few programmers care to detect such errors, but it can be done this way:
#include <limits.h>
...
sum = 0;
for (i = 0; i < N; i++) {
if ((sum >= 0 && arr[i] > INT_MAX - sum)
|| (sum < 0 && arr[i] < INT_MIN - sum)) {
fprintf(stderr, "integer overflow for entry %d\n", i);
return 1;
}
sum += ar[i];
}
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
scanf("%d",&ar[i]);
for(i=0; i<N; i++)
sum=sum+ar[i];
printf("%d\n", sum);
return 0;
}
This should be the code.
You have initially declared the array of size 0 (because i=0).
Even though you declared the array of size 0, when I ran it on my machine, it actually executed successfully with the correct output.
This is generally due to undefined behavior which means that we can only guess the output when the code is correct. If the code has undefined behavior, then it can do whatever it wants (and in the worst case the code will execute successfully giving the impression that it's actually correct).
Declaring a Variable Size Array (VLA) is optional in C11 standard. Thus, it depends on the implementation of the compiler whether it will support VLA or not. As pointed out by #DavidBowling in comments, if the compiler does support, then declaring a VLA of size 0 can invoke undefined behavior (which you should avoid in all cases). If it doesn't support, then this will simply give a compilation error and you'll have to declare the array size as some integer constant (example, int arr[100];).
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
}
for(i=0; i<N; i++)
{
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
You should declare the array after accepting the value of N.
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
As this is a very simple question I'll expand it a bit to include some good programming practices.
1. Analyze the problem
We have to complete two tasks here:
Read and store the numbers to array.
Sum the array elements.
Of course you can both read and calculate the same time, but we ❤ the SoC design principle. This will help you later with bigger programs.
2. Create the program structure
In this state we have to consider what function to use, as we already solved the data structure problem (we use array).
Of course, we always can put the whole procedure in main function but this would break the SoC principle.
The main principle here is:
I create a function for a separate procedure.
So we'll have to build two functions. Let's consider the following example:
ReadArrayData will be used to read the data from the standard input (your keyboard in other words) to array. But what will declare as parameters? We surely have to pass the array and the array size. The return type of this function will be void (we don't have to return something).
Keep in mind that if you pass array to function you can manipulate it as you please and keep these changes in your main program. This is because the arrays are passed always by reference to a function.
In the end this will be your function prototype:
void ReadArrayData(int arraySize, int array[]);
CalculateArraySum will be used to calculate the sum of the array elements. The function prototype will be the same as for ReadArrayData with the difference that the returning type will be int (we return the sum).
int CalculateArraySum(int arraySize, int array[]);
3. Write your program
#include <stdio.h>
void ReadArrayData(int arraySize, int array[]);
int CalculateArraySum(int arraySize, int array[]);
int main(void) {
int N;
printf("Give the array size: ");
scanf("%d", &N);
int array[N];
ReadArrayData(N, array);
int sumOfArrayElements = CalculateArraySum(N, array);
printf("The sum of array elements is %d.\n", sumOfArrayElements);
return 0;
}
void ReadArrayData(int arraySize, int array[]) {
printf("Give %d elements: ", arraySize);
for (int i = 0; i < arraySize; ++i) {
scanf("%d", &array[i]);
}
}
int CalculateArraySum(int arraySize, int array[]) {
int sum = 0;
for (int i = 0; i < arraySize; ++i) {
sum += array[i];
}
return sum;
}
I know this was a large scaled answer, but I saw you are new to computer programing. I just wanted to present you the main functionality to solve all kinds of problems. This was just a small introduction. In the end, you have to remember what steps we take to solve a problem. With time and as you solve many problems you will learn many many other things.

Segmentation fault:11, when I run C code

I am new in C programming. When I write a c code about sorting integers. I got a Segmentation fault: 11. I search the related articles, but seems too confusing for me. Here follows first part of my code(get 10 input integers, and derive all the odd integers). Can you help me?
#include <stdio.h>
int i;
int main(void)
{
int array[10];
int previous[10],odd[10];
printf("Pls enter 10 nums\n");
while(i < 10)
{
scanf("%d", &array[i++]);
}
for(i = 0;i < 10;i++)
{
printf("%d ", array[i]);
}
for(i = 0;i < 10;i++)
{
int a,j;
if(array[i] % 2 == 1)
{
previous[a] = i;
odd[j] = array[i];
a++;
j++;
}
}
}
The problem is with the variables a and j. In C you cannot be sure that when you declare them they will have the value 0.
If you don't give i and a initial values you will likely be attempting to go beyond the bounds of your array.

Strange behavior with simple C function

I have 2 simple functions, one function inputs in the the NxM array not including N+2 and M+2. So the original array must be surrounded by zeros and the other outputs the whole array. When the out function is called I have a very strange output:
But when I move the code to the main function everything is totally fine. I tried compiling this code in CodeBlocks and NetBeans.Behaviour is the same.
I don't know what's going on there. Can somebody explain?
.....
int main()
{
int array[N+2][M+2]={{0}};
local_in(N,M,array);
local_out(N,M,array);
return 0;
}
void local_in(int len, int len2,int arr[][len2])
{
int i;
int j;
for(i = 1; i <= len; i++)
for(j = 1; j <= len2; j++){
scanf("%d",&arr[i][j]);
}
}
void local_out(int len, int len2,int arr[][len2])
{
int i;
int j;
for(i = 0; i < len+2; i++){
for(j = 0; j < len2+2; j++)
printf("%d ",arr[i][j]);
printf("\n");
}
}
Your local_* functions pass the array as int arr[][len2]; but should use int arr[][len2+2] instead.
In general, the code should be much clearer if you passed the correct array dimensions around then implemented any policy on which items to read or write inside the local_* functions.

Resources