Problem with c++ code

dear forum members,

as the title reads, i have got a problem with a c++ code i wrote. i get no errors when i compile it and the program does what i want but in the end the console gives out strange errors...

this is the code:

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
#include <iostream>

int main()
{
  // input
  int n;
  std::cout << "n =?";
  std::cin >> n;
  int* arr;
  arr = new int[n];
  int input;
  std::cout << "Sequence of Numbers =?" << std::endl;
  for (int i = 0; i < n; ++i) {
    std::cin >> input;
    arr[i] = input;
  }
  
  //computation
  bool single = true;
  int k = 0;                   
  int* final_arr = new int[k];           
  for (int i = 0; i < n; ++i) {          
    for (int j = 0; j < k; ++j) {        
      if (arr[i] == final_arr[j]) {      
	single = false;                  
      }                                  
    }
    if (single == true) {                
      final_arr[k] = arr[i];             
      ++k;                               
    }
    single = true;
  }

  //output
  std::cout << "Without duplicates: "; 
  for (int i = 0; i < k; ++i) {
    std::cout << final_arr[i] << " ";
  }
  std::cout << std::endl;
  delete[] arr;
  delete[] final_arr;
  return 0;
}


*** glibc detected *** ./removeDuplicates: free(): invalid next size (fast): 0x08d72020 ***
Segmentation fault (core dumped)


could anybody please tell me what mistake i made?

thank you,

s
I see an array of size 0 at line 21

Never seen that kind of message, but segmentation faults happen when the program tries to access memory that it doesn't own or that is invalid
Last edited on
so am i not allowed to raise the array later on? what would a solution for that problem be? and if that is the problem, why is the program still compiling and actually working?

thank you for your answer!
so am i not allowed to raise the array later on?

That's right. C arrays have a fixed size

what would a solution for that problem be?

You can allocate some memory to it, and when the momory is full you allocate new memory larger that the previous, copy the data over and delete the old array.
Or you can use std::vector<int> that does all of this for you automatically

and if that is the problem, why is the program still compiling and actually working?

To be honest, I have no idea

thank you for your answer!

Glad to help!
Topic archived. No new replies allowed.