我一直在分段错误

时间:2016-04-09 14:54:10

标签: c arrays segmentation-fault malloc

我需要将名为vetor1vetor2vetor3的3个数组添加到一个名为conjunto的大数组中,但是当我发现时,我仍然会遇到分段错误运行代码。

我使用函数iniciaiza创建一个50位数组并用0填充此数组。然后,在函数read中,我将读取一个数组(大多数时候是数组的大小)将是3)并且在函数add中,我需要将三个数组复制到我使用malloc创建的数组。最后,我需要打印三个数组,并使用三个数组的副本。

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

int *conjunto;
int *vetor1, *vetor2, *vetor3, n1, n2, n3;
int tam = 50;

void inicializa (int **tconj, int tam)
{
    int i;
    *tconj = (int *) malloc (tam * sizeof(int));
    for (i = 0; i < tam; i++)
    {
        tconj[i] = 0;
    }
}

void read (int **vec, int *n)
{
    int i;
    printf("size of array: ");
    scanf ("%d", n);
    printf("array: \n");
    *vec = (int *) malloc (*n * sizeof(int));
    for (i = 0; i < *n; i++)
    {
        scanf ("%d", &(*vec)[i]);
    }
}

void add (int *conjunto, int *vetor1, int *vetor2, int *vetor3, int n1, int n2, int n3)
{
    int i, j, k, w;
    int fim1 = (n1 + n2);
    int fim2 = (n1 + n2 + n3);
    for (i = 0; i < n1; i++)
    {
        conjunto[i] = vetor1[i];
    }
    for (j = n1; j < fim1; j++)
    {
        conjunto[j] = vetor2[j];
    }
    for (k = fim1; k < fim2; k++)
    {
        conjunto[k] = vetor3[k];
    }
}

void print_array (int *vec, int n)
{
    int i;
    printf("array: ");
    for (i = 0; i < n; i++)
    {
        printf("%d ", vec[i]);
    }
    printf("\n");
}

int main()
{
    inicializa (&conjunto, tam);

    read (&vetor1, &n1);
    read (&vetor2, &n2);
    read (&vetor3, &n3);

    print_array (vetor1, n1);
    print_array (vetor2, n2);
    print_array (vetor3, n3);

    add (conjunto, vetor1, vetor2, vetor3, n1, n2, n3);

    print_array (conjunto, tam);

    return 0;
}

3 个答案:

答案 0 :(得分:2)

您的初始化功能几乎不错,只缺少一颗小星星:

void inicializa (int **tconj, int tam)
{
    int i;
    *tconj = (int *) malloc (tam * sizeof(int));
    for (i = 0; i < tam; i++)
    {
        (*tconj)[i] = 0;
    }
}

此外,您应该以这种方式阅读输入后在主电话中调用它:

tam = n1 + n2 + n3;
inicializa (&conjunto, tam);

在程序结束时,在return之前,您应该添加:

free(conjunto);
free(v1);
free(v2);
free(v3);

编辑:我错过了add()中的其他两个错误。

void add (int *conjunto, int *vetor1, int *vetor2, int *vetor3, int n1, int n2, int n3)
{
    int i, j, k;
    int fim1 = (n1 + n2);
    int fim2 = (n1 + n2 + n3);
    for (i = 0; i < n1; i++)
    {
        conjunto[i] = vetor1[i];
    }
    for (j = n1; j < fim1; j++)
    {
        conjunto[j] = vetor2[j - n1];
    }
    for (k = fim1; k < fim2; k++)
    {
        conjunto[k] = vetor3[k - fim1];
    }
}

编辑2:如果用户添加有趣的值(例如零或负大小的数组),它也将无效,我将这些控件保留给您。

答案 1 :(得分:1)

在您的add函数中,您正在阅读vetor2[j];vetor3[k];,但jk可以超出vetor < / p>

答案 2 :(得分:1)

for (i = 0; i < tam; i++)
{
    // This is not doing what you think it is.
    // You are setting some memory locations at and after tconj to zero,
    //  which is not the array you just allocated.  
    // The pointer to array that you just allocated is now 0
    tconj[i] = 0; // pretty sure you mean *tconf[i] 
}