2

I'm trying to create a function that would append two vectors together, but I end up getting a segfault when trying to reallocate more memory to the first vector so the second one would fit. Here's the code

void vectorAppend(double** v1, size_t* s1, double const* v2, size_t s2){
  assert(v1 && v2 && *s1 > 0 && s2 > 0);
  (*v1) = realloc((*v1), (*s1 + s2)*sizeof(double));
  for (size_t i = 0; i < s2; i++){
    *v1[*s1+i]=v2[i];
  }
  *s1+=s2;
}

And this is how I call it from main

double *v1 = vectorConstruct(3, 2);
double *v2 = vectorConstruct(3, 0);
unsigned int s = 3;
vectorAppend(&v1, &s, v2, 3);

vectorConstruct returns a pointer to a vector that is initialized to the second argument.

double* vectorConstruct(size_t s, double val){
  assert(s>0);
  double *ret = malloc(s*sizeof(double));
  for(size_t i = 0; i < s;i++){
    ret[i]=val;
  }
  return ret;
}

I can't seem to find the problem here so any answers are appreciated.

2
  • Have you tried running in a debugger? Commented Jun 14, 2012 at 13:16
  • You have unsigned int for s, but the parameter of vectorAppend is size_t the two are not guaranteed to be the same size Commented Jun 14, 2012 at 13:18

1 Answer 1

7
*v1[*s1+i]=v2[i];

should be

(*v1)[*s1+i]=v2[i];

Unary * has a surprisingly low precedence.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.