|
-
April 18th, 2002, 04:37 AM
#1
Memory leaks ?
Hi everybody,
A simple question. Someone told me that the following code creates inaccessible areas in memory. Tell me more please.
void MyFunc()
{
char* pMyString = "My string";
strcpy(pMyString, "Hello");
}
Many instructions and memory allocations are done by the above code :
- an area which content is "My string" is created, somewhere in the memory ;
- the address of this area is contained in the pMyString pointer.
The strcpy function creates another area and put the string "Hello" in it. Its address is now copy in the pMyString pointer. So, the first area ("My string") is now inaccessible.
My questions are simple :
- is it true ?
- if true, how can I do then ?
Thanks for your help.
-
April 18th, 2002, 07:27 AM
#2
Re: Memory leaks ?
void MyFunc()
{
char* pMyString = "My string";
strcpy(pMyString, "Hello");
}
This will not cause memory leaks - it will cause undefined behaviour (while undefined means it could do one of many things, it doesn't mean it could do anything, and memory leaks are not among those things that are a likely result).
When you compile, it places the literal "My string" someone in constant space - that is for the compiler to decide.
When you get the pointer to it in the above function, you are getting the pointer to this space.
And subsequently you are overwriting the memory, to which you should not have access.
This question has been asked many times before, by the way. If you do
char[] pMyString = "My string";
and then overwrite as you did before, it is safe, by the way, as they are different things. char[] and char* are not the same.
The best things come to those who rate
-
April 18th, 2002, 08:10 AM
#3
Thanks a lot
Thanks a lot for your response.
-
April 19th, 2002, 05:33 PM
#4
Re: Memory leaks ?
I am new here, can you explain the difference between char * and char[]?
Thanks
-
April 19th, 2002, 11:56 PM
#5
Re: Memory leaks ?
The first is a pointer, and the second is an array. Pointers and arrays are not the same thing.
When you say
char *p = "ABC";
You have declared 4 characters including the NULL, however, this is a constant. You can't modify it without invoking undefined behavior. For example, you can't strcpy() into it, or change any of the characters. If you ran your program on a Unix machine, you will see exactly what NMTop40 was talking about. The program would have more than likely caused a segmentation fault (a GPF in the Unix world) because you are writing to read-only memory. This is what is meant by "undefined behavior" -- anything can happen.
When you declare this:
char p[] = "ABC";
You have declared a modifiable array of characters.
Regards,
Paul McKenzie
-
April 20th, 2002, 11:53 PM
#6
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
|