Segmentation fault error (core dumped)

Good morning, everyone, how are you?

I have a problem to solve in C++Language:

" encode, in C, a vector addition program. The vector size N must be a command line argument in the program call. Use a random generator (rand) to create the vectors A and B, defined as float type. The Vector C, also float, should save the result of the sum: C = A + B. Show at the end the sum of all the elements of C. '

After searching, I managed to make the code that was needed, the problem is as follows: When I give values of N above 700 000 the program gives the following error - "segmentation fault (core dumped)".

I had to search and saw that it was a memory allocation problem, the problem is that I do not know how to solve this problem, since I do not have enough capabilities in C++.

Could you help me?

Below I leave you the code.

Thank you for your time!

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

int main(int argc, char *argv[]) { //Estes parametros permitem ao programa receber argumentos da linha de comandos
                         //argc guarda a quantidade de parametros
                         //argv vai guardar os endereços de memória dos inputs dentro de uma matriz


// 1 - Receber o tamanho do vetor
char *c = argv[1]; // Receber o valor de N como um char
int n = atoi(c); // Para depois converter para int


// 2 - Criar dois vetores com valores aleatórios e tamanho n
float A[n], B[n]; // Vetor A e B

srand(time(NULL)); // Gerar números aleatórios do tipo float

int i; // for

int tamanho = sizeof(A)/sizeof(A[0]); // Obter o tamanho dos vetores (o tamanho é igual para todos)

// Preencher o Vetor A com valores float entre 1 e 100
for (i = 0; i < tamanho; i++) 
{
    A[i] = rand() % 100 + 1; // rand() % max + min;
}


// Preencher o vetor B com valores float entre 1 e 100
for (i = 0; i < tamanho; i++)
{
    B[i] = rand() % 100 + 1;
}


// 3 - Somar os dois vetores e guardar o resultado da soma no vetor C
float C[n]; // Criar o vetor C

for (i = 0; i < tamanho; i++)
{
    C[i] = A[i] + B[i];
}


// 4 - Mostrar a soma de todos os elementos do vetor C
int soma = 0; // Variavel que vai guardar a soma

for (i = 0; i < tamanho; i++)
{
    soma+=C[i];
}
printf("A soma dos elementos do Vetor C é %d.\n",soma);







/*
// VERIFICAÇÃO DE RESULTADOS
// Verificar os valores do vetor A
printf("VERIFICAÇÃO DE RESULTADOS:\nVetor A\n");
for (i = 0; i < tamanho; i++)
{
    printf("Indice: %d --> Valor: %f \n",i,A[i]);
}

// Verificar os valores do vetor B
printf("Vetor B\n");
for (i = 0; i < tamanho; i++)
{
    printf("Indice: %d --> Valor: %f \n",i,B[i]);
}

// Verificar os valores do vetor C
printf("Vetor C\n");
for (i = 0; i < tamanho; i++)
{
    printf("Indice: %d --> Valor: %f \n",i,C[i]);
}
*/


return 0;
}
// O programa foi compilado numa máquina virtual Ubuntu com 8GB de RAM (Visto que é o objetivo do trabalho)
// Compilar Programa: gcc nome_ficheiro.c -o nome_output
// Executar Programa: ./nome_output
Author: Luis Amaro, 2019-06-06

3 answers

Possibly you are bursting your memory capacity as I see you are not accessing a position improperly.

See only:

A float occupies 4Kb.

Using the float vector size with 700 thousand positions, is 700000 x 4Kb = 2800000Kb = 2.8 Gb.

Multiplying by 3 vectors: 2.8 x 3 = 8.4 Gb.

Probably its RAM capacity is 8Gb.

If it's a problem for college, don't worry, your code is well done and correct.

If it is a personal project or you want to increase the size of the vector, you can do as follows:

Aloque apenas o vetor A; 
preencha ele por completo;
Imprime A (apenas por critério de verificar a validade do código).
Aloque vetor C;
Copie A por completo para C (C vira uma cópia exata de A);
Desaloque A por completo;
Aloque B;
Preencha B;
Imprima B;
Some o conteúdo de C com B ( C[i] += B[i]);
Imprima C;

This will reduce the amount of data stored in memory to 2/3.

 1
Author: Rodrigo Richa, 2019-11-25 15:12:07

Use The Last generated core dump to do the analysis:

gdb programa core_dump

Use the commands below to extract useful information for analysis:

bt
bt full
info threads
thread apply all bt
thread apply all bt full

If your problem is more complex, you can use this Google library that allows you to generate core dump in your own code:

https://code.google.com/archive/p/google-coredumper/
 0
Author: lsalamon, 2019-06-06 18:13:15

Most likely the problem was caused by "Stack Overflow".

Local variables (i.e. declared within a function) typically use a memory space called a "stack" (commonly also called a "stack" in English). The size of this" stack " is fixed for each program, and 1 MB is a common value.

The solution in this case is to create the arrays in Dynamic Memory through the "malloc"function. Memory allocated through the "malloc" function is not subject to stack size restrictions.

// 2 - Criar dois vetores com valores aleatórios e tamanho n
// float A[n], B[n]; // Vetor A e B
float* A = malloc(n*sizeof(float);
float* B = malloc(n*sizeof(float);
 0
Author: zentrunix, 2019-09-29 12:00:38