[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 233
  • Last Modified:

Why does this code return jibberish? C++

It worked in one program, but doesnt work in another.. it just returns jibberish

New program is /MD /clr
Multibye character set.


char * getConnection() {

      FILE *fi;

      fi=fopen("dbcon.ini","r");
      if (fi==NULL) {fputs ("FILE: dbcon.ini not found\n",stderr); exit (1);}
      char cn[500];
      fgets(cn,500,fi);
      fclose(fi);
      
      return (cn);

}
0
bail3yz
Asked:
bail3yz
  • 2
1 Solution
 
Let_Me_BeCommented:
You are returning a local variable that will cease to exist once the function returns.
0
 
bail3yzAuthor Commented:
Interesting... how come it worked in 1 program ?  
Should I be using a global variable?  I am confused :( lol
0
 
Let_Me_BeCommented:
Well, theoretically, you could use a global variable, but its something that is highly unrecommended.

You should allocate a new memory block (using malloc()) and return it.
Don't forget to free it after you are done with it.

Or you could pass the memory from the function where you are calling the getConnection() function (this can be a local variable if you won't return it from the function) as a parameter.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now