wrong dynamic array size

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
#include <iostream>
#include <time.h>
#include <conio.h>
#include <windows.h>
using namespace std;

class name_box{
private:
char line[20];
int chars;
public:
name_box(){chars=0; clean();}
~name_box(){}
void clean() {chars=0; int i=0; while (i<20){line[i]=' '; i++;}}
void add(char c) {if (chars<=19) {line[chars]=c; chars++;}}
void back() {if (chars>0){chars--; line[chars]=' ';}}
char* out() {char *f; delete f; f=new char[chars]; int i=0; while(i<chars){f[i]=line[i]; i++;} return f;}
};


int main (void)
{

name_box na;
na.add('L');
cout<<strlen(na.out())<<endl;
na.add('B');
cout<<strlen(na.out())<<endl;
na.add('K');
cout<<strlen(na.out())<<endl;
na.add('M');
cout<<strlen(na.out())<<endl;
na.add('R');
cout<<strlen(na.out())<<endl;
na.add('Z');
cout<<strlen(na.out())<<endl;
na.add('M');
cout<<strlen(na.out())<<endl;
na.add('R');
cout<<strlen(na.out())<<endl;


system("PAUSE");
return 0;
}


In function "out" array *f is not of size "chars" as it should be. why? and what can i do with it?
On line 17 you delete a char* with no value. This causes undefined behaviour and is dangerous.

You should ONLY delete a pointer that is set to 0, NULL or that has already beel allocated with new.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
char* f; // create pointer, its value has not been set and is undefined

delete f; // VERY BAD! who knows what f is pointing to? It could be anywhere in memory.

char* g = 0; // create pointer initialised to 0. GOOD PRACTICE!!

delete g; // GOOD, no harm comes by deleting a zeroed pointer

char* h = new char; // create a pointer pointing to a single char

delete h;// GOOD, delete the char we created with new

char* i = new char[100]; // create a pointer pointing to an *array* of characters.

delete i; // BAD!! our pointer is pointing to an *array* that we allocated with new[], so we must delet with delete[]

char* j =  new char[100]; // create a pointer pointing to an *array* of characters.

delete[] j; // GOOD!! we created with new[], and we deleted with delete[]

Last edited on
Topic archived. No new replies allowed.