-3
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>


int cauta(const void *x, int n, int dim_el, const void *el)
{
  char *c = (char*) x;
  int i;
  for(i = 0; i < n; i++)
  {
    if(memcmp(c + i * dim_el, el, dim_el) == 0)
      return 1;
  }
  return -1;
}

int main()
{
  int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
  int k;
  k = cauta(a, sizeof(a) / sizeof(a[0]), sizeof(a[0]), a[0]);
  printf("%d", k);
  return 0;
}

The problem appears on the commented line. The function returns 1 if "el" exists in the "x" array . It's a simple, yet I don't understand exactly why it's a segmfault.

Also, this is the call stack display when I tried debugging it line by line.

Michael
  • 876
  • 9
  • 29

2 Answers2

4

In your code, the function parameters are

 int cauta(const void *x,int n,int dim_el,const void *el)

where el expects a const void *, whereas, while calling,

cauta(a,sizeof(a)/sizeof(a[0]),sizeof(a[0]),a[0]);

you passed a[0] which is an int.

You need to pass an address, like &a[3], for example.

That said, int main() should be int main(void) to conform to the standards.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You're passing in an int i.e. a[0] into cauta as an const void * that's going to cause the error.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54