Results 1 to 3 of 3

Thread: Dynamic memory/ leaks

  1. #1

    Thread Starter
    Member
    Join Date
    Apr 2008
    Posts
    42

    Dynamic memory/ leaks

    Code:
    #include <stdio.h>
    #include <malloc.h>
    char* Hello();
    int main()
    {
    printf("%s\n",Hello());
    return 0;
    }
    
    char* Hello()
    {
    char* pHello = (char*)malloc(6);
    pHello = "HELLO";
    return pHello;
    };
    Will this cause a memory leak? Would the best way to be like :

    Code:
    #include <stdio.h>
    #include <malloc.h>
    char* Hello();
    int main()
    {
    	char* sHelloString = Hello();
    printf("%s\n",sHelloString);
    free(sHelloString);
    return 0;
    }
    
    char* Hello()
    {
    char* pHello = (char*)malloc(6);
    pHello = "HELLO";
    return pHello;
    };
    Is there ANY other way I can return a character string from a function without it losing its memory address, apart from using std::string? Sorry, just haven't quite grasped the concept..

    And if I get a memory leak, what is the worst that could happen outside of my program? Because last time I did something before I learned about the free() call, I made a program that had LOTS of memory leaks and my computer started acting weird, stuff wouldn't copy,mouse would randomly click etc and I had to reboot. Just a coincidence? Or from memory leaks. Thanks.

  2. #2
    Frenzied Member
    Join Date
    Sep 2005
    Posts
    1,547

    Re: Dynamic memory/ leaks

    well you can use char * pHello = new char[6]; but other then that, as long as you free somewhere your fine.

    Memory leaks are only bad if you have a function you call a lot and you don't free any of the memory used by it.

  3. #3
    G&G Moderator chemicalNova's Avatar
    Join Date
    Jun 2002
    Location
    Victoria, Australia
    Posts
    4,246

    Re: Dynamic memory/ leaks

    Quote Originally Posted by high6
    Memory leaks are only bad if you have a function you call a lot and you don't free any of the memory used by it.
    I can't begin to tell you how terrible that theory is..

    While it is true things should be fine if you free them "somewhere", you should never pass dynamically allocated memory from a class. Keep to the mindset that, wherever you allocate memory, you should also remove it.

    chem

    Visual Studio 6, Visual Studio.NET 2005, MASM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width