char array mysteriously changing name

I'm trying to use a function to create a filename, but somehow the char array changes (a '3' is added) between running the function and back in main(). Here's 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
using namespace std;
#include <iostream>    
#include <sstream>
#include <fstream>   
#include <string.h>

void filename(int, char*&);

int main() {

	int N=100;
	char *cname;

	ifstream positions;
	filename(N, cname);
	positions.open(cname);
	cout << "in \"main()\": " << cname << endl;
	
}
	
	
void filename(int N, char *&cname) {

	string name;
	stringstream number;
	int i;
	
	number << N; 
        name="1,2bN"+number.str()+".dat";
	
	cname=new char[name.length()];
	for(i=0;i<name.length();i++) cname[i]=name[i];
	cname[name.length()]=0;
	cout <<  "in \"filename()\": " << cname << endl;
}


The output is:
in "filename()": 1,2bN100.dat
in "main()": 1,2bN100.dat3

The strange thing is it has worked perfectly for other values of N (lower, with two digits only) but not N=100. Suggestions?

edit: clarity
Last edited on
Line 31 should allocate name.length() + 1 characters to allow for a null char. You're currently writing unallocated memory in line 33.

You should also use strncpy() to copy one string into another instead of using a FOR loop.

Finally, you should really be using std::string in main() as well instead of using a 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
void filename(int, char*&);

int main() {

	int N=100;
	char *cname;

	ifstream positions;
	filename(N, cname);
	positions.open(cname);
	cout << "in \"main()\": " << cname << endl;
	delete cname;
}
	
	
void filename(int N, char *&cname) {

	string name;
	stringstream number;
	int i;
	
	number << N; 
        name="1,2bN"+number.str()+".dat";
	
	cname=new char[name.length() + 1];
	strcpy( cname , name.c_str());
	cname[name.length()]= '\0';
	cout <<  "in \"filename()\": " << cname << endl;
}
Of course, how could I miss that!

The reason I'm using char arrays: I will use these together with functions I wrote before discovering the c_str() function of the string class; and need char arrays in use with some other standard mpfr-functions. I'm too lazy to rewrite everything.

Thanks!
Topic archived. No new replies allowed.