deleting char array

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
49
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main()
{
char str[100];
char *buffer;
int i,j;


FILE * fp;
fp = fopen("fast.txt","w");

for(j=0;j<50;j++)
{
buffer = new char[50000];
//buffer[0] = '\0';
cout << strlen(buffer) << "   ";

for(i=0;i<500;i++)
{
sprintf(str,"%d %d %d %d %lf %lf\n",i,i+100,i+2000,i+3000,(rand()%10000)/100000.00,(rand()%10000)/100000.00);
//cout << str << "\n";

if ( i == 0 )
strcpy(buffer,str);
else
strcat(buffer,str);

}

//cout << buffer << "\n";
cout << "length = " << strlen(buffer) << "\n";

fwrite(buffer,1,strlen(buffer),fp);
delete [] buffer;
//cout << buffer << "\n";
cout << strlen(buffer) << "\n ";

}

fclose(fp);

return 0;
}



In the above code the old buffer is deleted each time and new memory is assigned. But strlen(buffer) returns the size of the string which was before deleting. Also even after 'delete [] buffer' when I stdout buffer I get the entire array which was stored before calling delete. I know I can just set buffer[0] to '\0', but I want to know what is wrong in the above code.
When you called new, a block of 50,000 characters was obtained and it's address was returned and stored in the pointer named buffer.

When you deleted the buffer, you told the memory routines you were no longer using that block of memory, however the pointer named buffer still had the address of that block of memory. Deleting a block of memory does not change any pointers you may have set in your program. However, it is a no-no to reference that memory (as you did in the strlen()) once you've returned that memory.

Ah! That explains. Thanks AbstractionAnon
Topic archived. No new replies allowed.