Why does this code return jibberish? C++

Posted on 2009-12-16
Last Modified: 2012-05-08
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;

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

Question by:bail3yz
    LVL 12

    Expert Comment

    You are returning a local variable that will cease to exist once the function returns.

    Author Comment

    Interesting... how come it worked in 1 program ?  
    Should I be using a global variable?  I am confused :( lol
    LVL 12

    Accepted Solution

    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.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
    Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
    The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now