-
July 6th, 2005, 01:18 PM
#1
memory leakage
Hi:
I have a question about memory alloction and collection in C.
If I write a function like this:
................
char * temp ;
temp= (char * )malloc(1024);
strcpy(temp, "123");
printf("%s", temp);
free(temp);
.............
are there going to be memory leakage? thank you.
-
July 6th, 2005, 01:22 PM
#2
Re: memory leakage
Only if you return from the program/function and the free() call doesn't get reached at all. But this code doesn't leak. Even there would be a nicer way to prevent form leaking:
Code:
char temp[100] = {0} ;
strcpy(temp, "123");
printf("%s", temp);
You should use dynamic allocation only when absolutely needed. Of cause of when the size of the buffer is not known.
-
July 6th, 2005, 01:50 PM
#3
Re: memory leakage
thanks for your reply.
the reason I am using it this way is that I don't know the size of it when I try to allocation the memory.
I am wondering, in case of above sample, how does the runing env knows that it is a larger size memory than it is acturally used.
-
July 6th, 2005, 01:57 PM
#4
Re: memory leakage
Originally Posted by jzhang0502
the reason I am using it this way is that I don't know the size of it when I try to allocation the memory.
But never forget to clean up any resources...
Originally Posted by jzhang0502
I am wondering, in case of above sample, how does the runing env knows that it is a larger size memory than it is acturally used.
Well it the language and the compiler don't care about the size of the buffer. If you want to write to "temp"'s array place 110 then you will write to temp's array place 110. But well... If it will works is another thing. The functions (strcpy, sprintf) don't even care about the size of the buffer either. So if you call strcpy and specifiy a buffer that is not large enough to handle the string copied into it, it will simply write out of bounds. And if the buffer is larger than the string copied into it? Well the rest of the buffer simply won't be used - thus you have a small amount of memory wastement. The C functions know how much buffer is used by simply terminating the string with a null-terminator. Thus "abc" would actually look like this.:
Code:
char sz[] = "abc"; // is the same as
char sz[] = {'a', 'b', 'c', '\0' }
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
|