Error of Segmentation fault (dumped core)

Asked

Viewed 2,036 times

0

Good morning to you all, as you are?

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 call to the program. Use a random generator (Rand) to create vectors A and B, defined as float type. The vector C, also float, should store the sum result: C = A + B. Show at the end the sum of all the elements of C."

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

I had to research 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++.

I wonder if you could 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

3 answers

1


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

Look at that:

a float occupies 4Kb.

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

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

Probably its RAM capacity is 8Gb.

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

If you are a personal project or want to increase the vector size, you can do it 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 way you will reduce the amount of data saved in memory to 2/3.

0

Most likely the problem was caused by "stack burst".

Local variables (i.e., declared within a function) typically use a memory space called a "stack" (commonly also called a "stack" even 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 via "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

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, Voce can use this google library that allows you to generate core dump in your own code:

https://code.google.com/archive/p/google-coredumper/
  • When running my program I do not see the file containing the core dump, and for what I had to search, to use gbd we need that file to do the analysis.

  • The recording location may vary depending on your dist. linux, but try these paths: /var/lib/systemd/coredump/, [/proc/sys/kernel/]core_pattern, /var/spool/abrt/,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.