Losing part of char array returning from function by reference

The contents of the array are safe within the function, however, upon returning to main the data becomes garbled.

section of main:

unsigned short tcp_port = atoi("8080");
const char* workDir = "WhatInthe?";

// Parse command line arguments

if ( parseCmdArg( tcp_port, workDir, argc, argv) == 1)
return 1;

cout << argc << endl;
cout << tcp_port << endl;
cout << workDir << endl << endl << endl;
cout << workDir << endl << endl << endl;

section of function code:

int parseCmdArg( unsigned short &tcp_port, const char* &workDir, int argc, char* argv[])
{

char tempPath[256];
bool pathDef = 1;

cout << "pCA tcp_port start: " << tcp_port << endl;
cout << "pCA wordDir start: " << workDir << endl;
cout << "pCA argc start: " << argc << endl;

*/ Command line process takes place here /*

if ( pathDef == 1 )
{
cout << "workDir = NULL" << endl;
getcwd(tempPath, 256);
workDir = tempPath;
}

cout << "pCA tcp_port exit: " << tcp_port << endl;
cout << "pCA wordDir exit: " << workDir << endl;
cout << "pCA tempPath exit: "<< tempPath << endl;
cout << "pCA argc exit: " << argc << endl;

The output to console is:

pCA tcp_port start: 8080
pCA wordDir start: WhatInthe?
pCA argc start: 1
workDir = NULL
pCA tcp_port exit: 8080
pCA wordDir exit: /user/ghesquie/cse422/lab3
pCA tempPath exit: /user/ghesquie/cse422/lab3
pCA argc exit: 1
1
8080
/user/ghesqui?
????????


/user/ghesqui? ??

So exiting the function the char array at pCA wordDir exit: is correct, but main show the first 13 characters, but the rest is garbled?

Any suggestions,

Thank you in advance,

Tex

In the future, please put your code in code tags:

[code]
Put your code here
[/code]

Anyway your problem is a problem of scope and/or misunderstanding pointers.

In your parseCmdLine function, you're changing 'workDir' to point to 'tempPath'. When the function exits, 'tempPath' is destroyed because it is a local variable, and therefore 'workDir' becomes a bad pointer because what it points to no longer exists.

You're better off using strings:

1
2
3
4
5
6
7
8
9
10
string workDir;

//...

int parseCmdArg( unsigned short &tcp_port, string& workDir, int argc, char* argv[])
{
//..
  workDir = tempPath;
//..
}


Those changes should work just fine
Topic archived. No new replies allowed.