|
-
Jul 20th, 2008, 12:15 AM
#1
Thread Starter
Member
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.
-
Jul 20th, 2008, 12:57 AM
#2
Frenzied Member
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.
-
Jul 20th, 2008, 10:11 PM
#3
Re: Dynamic memory/ leaks
 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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|