program keeps crashing at stdin reading

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#include <stdlib.h>

static void binsortu(const int N);
int compare (const void* a, const void* b);

int main()
{ 
  //test binsortu call
  binsortu(4);
  return 0;
}

int compare (const void* a, const void* b)
{ 
  //*(char*)a - *(char*)b
  //or memcmp?
  return 0;
}

static void binsortu(const int N)
{
  
  char* c_array;
  int i = 0, j;
 
  c_array = (char*) malloc(N*sizeof(char));

  while ((c_array[i] = getchar()) != EOF)
  {  
    //check if need a realloc 
    if( (i%N) == 0)
      c_array = (char*) realloc(c_array, N*sizeof(char));    
    i++; 
  }

  //sort here
  //use memcmp to get rid of copies
  //qsort(c_array, i+1, N, compare);

  for(j=0; j<i+1; j++)
    printf("%c", c_array[j]);

  free(c_array);
 
  return;

}


hey im doing a little sorting program in C. i havent programmed in C for a long time so im a bit rusty. im reading in N bytes of a character string from stdin and then sorting, removing duplicates (using memcmp) and outputting to stdout. i need to use malloc and realloc (the input is always growing until eof).
1) my program keeps crashing after a four or five inputs and i have no idea why.
2) once i detect there is a dupe with memcmp how can i remove the dupe? am i having the right idea of using memcmp first to remove dupes and then using compare in qsort to sort it?

thanks for looking
Line 33: you never increase the size of your c_array. You need to keep track of the current size somehow. Then realloc(c_array, current_size + N*sizeof(char)).
Topic archived. No new replies allowed.