Malloc in C copying previously allocated strings? - c

When i use malloc in C, i use it within different functions and free the pointers i used in malloc outside of the function.
Function 1: allocates memory for a point that is a string "hi" it returns the pointer that has "hi"
function 2: I have a pointer and allocate memory for this pointer, it then contains "hi" too. Even though i haven't done anything to this pointer.
Why does this happen? How do i stop this?
I've tried to reallocate memory and free multiple times but nothing works.

Your question is unclear. If you are allocating memory with malloc, the library does not initialize the memory to which a pointer is returned. It may contain anything: in your case, it may well contain the same string, but is does not mean anything.
Post your code so we can confirm this diagnostic.

Related

What Happens If You Set Allocated Memory To NULL in C

Is there a difference between setting a pointer to NULL before and after allocating it?
For example, is there any difference between
char* c = NULL;
and
char* c = malloc(sizeof(char));
c = NULL;
What are the, if any, implications of each of those statements, and is there any difference in calling free(c) in each of those situations?
Let's look at the two cases.
Case 1: Before malloc
Well, there's almost no harm done here. Unless the pointer was pointing to something before, the pointer is simply set to NULL and points to nothing. Calling free() on a pointer that points to nothing does nothing. "Free the people?" Okay. "Free the free?" You can't really free something that's already sort of "free." No stranger, no danger. Moving on...
Case 2: After malloc
Let's break it down:
char* c = malloc(sizeof(char));
c = NULL;
The first command will reserve memory from the operating system for your program. That's dynamic allocation--getting more memory on the fly.
The second command sets your pointer to NULL. What does that mean?
Memory leak. That means your program has basically borrowed memory from the operating system and forgot about it. This is a big no-no. If a program keeps doing it over and over, they will eventually crash (or the entire system will crash).
Just like how you should always return things to friends, you should always return memory to the operating system. Therefore, you must always call free() for every point you malloc(); just like opening and closing brackets (), [], or {} in C or C++.
Never set a pointer to NULL until after you free() the memory associated with it.
Before allocating it, it might have (depending on where it was declared) garbage data in it. By assigning it to null before, you basically assure it is in a known good state.
After allocating and assigning the address to a variable, setting the pointer to null means that the pointer will no longer reference the allocated memory. Normally this creates a memory leak (a bit of allocated memory that cannot be referenced anymore, and so it cannot be freed). However there are times were this is appropriate. For example, if your logic has two references to the memory, one for allocation / deallocation purposes and one for "current item of interest" it might be appropriate to assign the current item of interest and then assign null to it as this "current item of interest" pointer is not related to memory allocation and deallocation.
Finally, if it is a pointer to be used for deallocation, after you free() the pointer, you might want to then set the pointer to null for the same reasons you set the pointer to null prior to allocation (to make sure that your program doesn't get confused by finding an address value in the pointer when that's not memory you want accessed).
Yes there's a difference. The second one causes a memory leak.
As to your second question, if c = NULL, then free(c) will have no effect.
You're not setting the allocated memory to NULL, you're setting the pointer to NULL so that it no longer points to the memory that you allocated. When you call free on it, you're not freeing the memory that you allocated, since the pointer doesn't point to it.
This is called a memory leak: you've allocated some memory, but you no longer have a pointer to it so you can't free it, so the memory will remain "in use" and unavailable to other programs even though you're not actually using it anymore.
Calling free on a NULL pointer has no effect.

What's the best method to free memory?

I'm working on ANSI C.
I have a string object which created with array of char..
I think the object make a memory leak..
when I run my program about five minutes (maybe almost 10000 iteration) my used memory become bigger and bigger..
I tried to free my object used memory with free and delete function. but, delete isn't a valid function. in the other side, free looks like running well first. but I got free():invalid pointer..
How can I fix this? I can do it differently?
here's a little of my code..
char *ext;
ext = calloc(20, sizeof(char));
//do something with ext
free(ext);
In C, you allocated memory on the heap with malloc, and release is with free. So you are correct there. delete is used in C++, and then, only if the memory was allocated with the new operator.
If you are getting an invalid pointer error in your call to free, then there is likely a bug somewhere in the code, if you post it we could take a look at it.
Maybe you're writing past the end of the allocated memory. With
calloc(20, sizeof(char))
you allocate space for 20 characters (19 "regular" and a null terminator for strings).
Make very sure none of your strcat() try to write "regular" characters beyond str[18].
Without more code:
An array in memory just prior to what ext points to overran its storage and corrupted a type of "header" that malloc() uses to track the size of the memory for subsequent calls to free() (think of ((size_t *)ext)[-1] holding the size from the malloc).
You used a negative array index into ext[negative] that did the same corruption.
ext somehow gets modified.

Should this C pointer be released?

Please excuse my C newbiness.
Consider the following C procedure:
int doSomething() {
char *numbers="123456";
...
}
Before this procedure exits should I be releasing the 'numbers' pointer?
No, you didn't malloc it. Why should you release it?
Often, the string is placed in a read only section of the executable.
In C language you don't and can't "release" pointers. Pointers are ordinary scalar variables. There's nothing you can do with them in terms of "releasing" or anything like that.
What one can be "releasing" is the memory a pointer is pointing to. But in C you only have to release memory that was explicitly allocated by malloc/calloc/realloc. Such memory is released by calling free.
Note again, that in your program you might have several (a hundred) pointers pointing to the same block of allocated memory. Eventually, you'll have to release that memory block. But regardless of how many pointers you have pointing to that block, you have to release that memory block exactly once. It is your responsibility to make sure that you release it. And it is your responsibility to make sure you released it exactly once. I'm telling you this just to illustrate the fact that what you release is the memory block, not the pointers.
In your example, your pointer points to a memory block that was never allocated by any of the aforementioned functions. This immediately means that you don't need to release anything.
No, there is no need to do so, and doing so is incorrect (thanks dmckee). The character string will be in the data segment of the binary, so it can't be freed. The memory was not dynamically allocated.
"numbers" will be on the stack, so it will go away when the function returns.
you don't actually need to call delete or free , these operators are only used to clean up memory that have been allocated my runtime memory allocator like malloc, calloc , GlobalAlloC, HeapAlloc and so forth. When you define a pointer like in the example you are actually allocating space for array of character in the the execuatable file. so bigger the string length bigger will be the executable size thus increasing your working set.
No; there's nothing to release. The string literal "123456" is an array of char (const char in C++) with static extent. The memory for it is allocated at program startup and held until the program exits. All you've done is assign the address of the string literal to numbers; you haven't actually allocated any memory.
NO, since it was not allocated by malloc/ calloc / realloc.
It will be automatically "freed" because it is an automatic variable.
No, it points to pre-allocated memory in process data segment. Only free(3) what you have malloc(2)-ed (modulo some library functions like getaddrinfo(3)/freeaddrinfo(3).)

how 'free' works when pointer is incremented

When malloc is called, the size is stored adjacent to the allocated block so that free will know how much to free etc ( http://c-faq.com/malloc/freesize.html ).
My question is, Say we have dynamically allocated memory and later in the code we increment the pointer
pointer++
And then later, if i call a
free(pointer)
what memory does actually get freed up.
Is it number of allocated bytes starting from the current address pointed by 'pointer' or from the base address to which it has been allocated.
You need to free() the same pointer as you received from malloc(). Incrementing, altering or changing it is undefined behaviour, that is usually a segmentation fault.
Think of the pointer you receive as a book from a library. You get home and read it. Afterwards you remove the front page and the book's back and hand it back to the librarian. Will he accept it or are you in serious trouble now? ;-)
You can only call free() on a value that you previously obtained from malloc(), calloc(), or realloc() (or NULL). Everything else is undefined.
For example, an implementation might store the size of the allocated block in 4 bytes before the return address from malloc(). Then, free() goes back 4 bytes and finds out the size. This wouldn't work if you don't pass the original pointer back to free().
It will cause undefined behavior. Most likely it will crash your program either instantly or later.
That's undefined behavior. And it will most probably results in problem later on.
If you increment the pointer without saving the original malloced location you can't call free on it. You have to save the original location somewhere and use a temporary point when you increment.
doing pointer++ to original pointer is terribly wrong. result of freeing it may be different on different implementations, but you definitely shouldn't do it.
The code managing the free storage just assumes that you wouldn't hand it the wrong pointer. It takes whatever you give, doesn't check its plausibility, and interprets it the same way it would interpret the right pointer. It will act according to whatever values it reads from whatever memory locations it looks at assuming the pointer was rightfully obtained. If you handed it a stray pointer, it will find nonsensical values and thus act nonsensical.
This is called undefined behavior and it's a mean thing. It might format your hard drive, toast your CPU, or make your program seemingly work the way it is expected to until you retire. You never know.
This is what we call a memory leak/segmentation fault.
You HAVE to pass the same pointervalue to free() as the one you got from malloc() or your application will misbehave/crash.
The pointer returned by malloc() points directly to the memory on the heap that will be used by your program.
However, this isn't the only memory that's allocated. A few bytes are allocated in the memory locations immediately preceding the pointer returned that indicate the size of the chunk on the heap. This isn't used by your program, but it will definitely be needed by free.
When free(p) is called, the information about its chunk on the heap is contained in, say, the locations from p-4 through p-1. This depends on implementation of course, but the details need not concern the programmer. The only thing that the programmer needs to know is that free uses that area of memory to free the chunk of memory from the heap, and that area is derived from the original pointer p.
In other words, if you call free on p, it will only make sense if malloc once returned exactly p.
If you pass in a pointer that wasn't created with malloc, who knows what will lie at p-1, p-2, etc.? It will probably result in a catastrophic failure.

Is the memory of a (character) array freed by going out of scope?

Very much related to my previous question, but I found this to be a separate issue and am unable to find a solid answer to this.
Is the memory used by a (character) array freed by going out of scope?
An example:
void method1()
{
char str[10];
// manipulate str
}
So after the method1 call, is the memory used by str (10 bytes) freed, or do I need to explicitly call free on this as well?
My intuition tells me this is just a simple array of primitive types, so it's automatically freed. I'm in doubt because in C you can't assume anything to be automatically freed.
In this case no you do not need to call free. The value "str" is a stack based value which will be cleaned up when that particular method / scope is exited.
You only need to call free on values which are explicitly created via malloc.
It is automatically freed. If you didn't malloc it, you
don't need to free it. But this has nothing to do with it being
a "simple array of primitive types" - it would be freed if it was
an array of structures. It is freed because it is a local variable.
Given that you are asking these very basic questions,
I have to ask which C textbook are you using. Personally, I don't believe that you can usefully learn C without
reading Kernighan & Ritchie's The C Programming Language, which
explains all this stuff very clearly.
Yes, it is "freed." (Not free()'ed, though.)
Since str is an automatic variable, it will only last as long as its scope, which is until the end of the function block.
Note that you only free() what you malloc().
Yes, the memory is freed automatically once method1 returns. The memory for str is allocated on the stack and is freed once the method's stack frame is cleaned up. Compare this to memory allocated on the heap (via malloc) which you must explicitly free.
No, local variables of this sort are allocated on the stack, so when you return from the procedure the memory is available for the next function call, which will use the memory for its stack frame.
If you use malloc() the space is allocated on the heap, which must be explicitly freed.
I think it's freed not because it's primitives but that it's a local variable and that will be allocated on the stack not the heap. If you don't malloc it then you can't free it as far as I remember.
I'm a bit rusty in C/C++ lately, but I think you're right. As long as you didn't dynamically allocate that memory, you should be fine.
Yes, it is "freed" when it goes out of scope.
No, you don't have to explicitly free it.
The char array is allocated on the stack, so when you return from the function, that stack space is re-usable. You do not need to explicitly free the memory.
Good rule of thumb: if you malloc, you must free.

Resources