[SOLVED] Program stops working after i call a function that returns a pointer in C

Issue

I have to create a function that, given 2 different values s1 and s2 (s1<s2) and a vector filled by a file, creates a new vector and arranges the values (a) of the first vector putting the a<s1 elements at the start of the new vector, followed up by the values s1< a < s2 and in the end the values a>s2 and prints the initial vector and the new one

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

#define DIM 11

void printVect(double *);
double *functB(double *vectPtr);

int main()
{
    FILE *fp;
    double vect[DIM], *Ptr;
    double newvect[DIM], *nvPtr;

    Ptr=(double*) malloc(sizeof(double)*DIM);

    fp=fopen("dati.txt", "r");  

    for(int i=0; i<DIM; i++)  
    {
        fscanf(fp, "%lf", &Ptr[i]);
    }
    printVect(Ptr); 
    puts("\n");

    *newvect=*functB(Ptr);
    printVect(newvect);
}

void printVect(double *vector)
{
        for(int i=0; i<DIM; i++)
    {
        printf("%10.2lf", vector[i]);
    }
}

double *functB(double *vectPtr)
{
    int s1=2; int s2=5; int n=0;
    double *newVect;
    for(int i=0; i<DIM; i++)
    {
        if(vectPtr[i]<s1)
        {
            newVect[n]=vectPtr[i];
            n++;
        }
    }
    for(int i=0; i<DIM; i++)
    {
        if(vectPtr[i]<s2 && vectPtr[i]>s1)
        {
            newVect[n]=vectPtr[i];
            n++;
        }
    }
    for(int i=0; i<DIM; i++)
    {
        if(vectPtr[i]>s2)
        {
        newVect[n]=vectPtr[i];
        n++;
        }
    }
    return newVect;
}

the output i get is

 10.00      2.30      4.56      2.00      1.23      8.65     10.00    -12.30      4.34     16.22      2.30

so the program only prints the first vector and stops working after

 printVect(Ptr); 
    puts("\n");

i guess the problem is with the functB function but i can’t figure out what the problem is

Solution

Within functB, you return and mutate the newVect that is defined but not initialized.

double *newVect = malloc (DIM*sizeof(double));

if (!newVect) generate_error_and_return();

else your code.

Answered By – alinsoar

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.