How come I don't get any error using the following program?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char *pStr = (char*) malloc(25);
free(pStr);
strcpy(pStr, "foo");
printf("%s\n", pStr);
return 0;
}
Shouldn't free(pStr) stop me from writing to that address? Don't I have to allocate the space again before I can use it?
free doesn't prevent you from doing anything as long as the thing is syntactically correct. So you are still more than welcome to copy to a char* just as you could do if you had never allocated the memory in the first place. But this is undefined behavior, and is liable (read: likely) to cause your program to crash or do something wrong without warning.
For example, if your compiler does some optimizations, it might reorder some instructions in order to save time. Since you have freed the memory, the compiler might think that it is safe to allocate memory in that location for some other data that will be created later. If the optimizer moves that allocation and write to before your strcpy here, you could overwrite the object that is stored there.
Consider this code:
int main(int arc, char *argv[]){
char* pStr = (char*) malloc(25);
free(pStr);
strcpy(pStr, "foo");
printf("%s\n", pStr);
int* a = (int*) malloc(sizeof(int));
*a = 36;
printf("%d\n", *a);
}
Since you wrote to unallocated memory, you can't be sure what either of the printfs will display. The 36 might possibly have overwritten some of the "foo" string. The "foo" string might have overwritten the value 36 that a points to. Or maybe neither of them affects the other and your program runs seemingly just fine until you change the name of some variable and recompile and for some reason everything is messed up even though you didn't change anything.
Moral of the story: you are correct that you should not write to freed memory; however, you are incorrect that you cannot write to freed memory. C does not check this condition and assumes that you are trying to do something fancy. If you know exactly how your compiler optimizes and where it allocates memory when malloc is called, you might know that writing to unallocated memory is safe in a particular case, and C does not prevent you from doing that. But for the 99.999% of the time that you don't know everything, just don't do it.
It is an undefined behavior. And what really happens is implementation specific.
In practice, free very often mark the freed memory block as reusable for future malloc-s.
See also this ...
As other answers pointed it's undefined behavior, thus compiler is not obligated for any diagnostics. However if you have modern version of gcc (>= 4.8) or clang, then AddressSanitizer might be helpful in case of this "use-after-free" bug:
$ gcc -ansi -pedantic -fsanitize=address check.c
$ ./a.out
=================================================================
==2193== ERROR: AddressSanitizer: heap-use-after-free on address 0x60060000efe0 at pc 0x4009a8 bp 0x7fff62e22bc0 sp 0x7fff62e22bb8
...
The common defensive programming "trick" is to assign NULL right after free() call:
free(pStr), pStr = NULL;
With it It's likely to get "Segmentation fault" with pStr dereference on GNU/Linux, but there is no guarantee on that.
Understand the answer to your question you need to understand the process of memory allocation. In a generic sense, malloc/free are library functions. They manage a memory pool that is allocated from operating system services.
[at the risk of oversimplification]
Your first malloc finds an empty pool. It then calls an operating system system service to add pages to the process that get added to the pool. Malloc then returns a block of memory from that pool.
Calling free returns the block to the pool. It remains a valid block of memory in the pool.
If you access the free'd address, the memory is still there. However, you are #$#$ing up malloc's pool of memory. That kind of access is going to eventually byte you in the #$#$.
Related
I'm reading a lot about malloc() and free() in Standard C. As I understand it, you malloc() for some memory exactly once and then you free() that same memory exactly once. It may be bad practice, but I understand that after you malloc() memory, you can define multiple pointers to it. And once you free() any of those pointers, the allocated memory is de-allocated?
Consider this toy example:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
char* p = (char*)malloc(10 * sizeof(char)); // allocate memory
int* q = (int*)p; // pointer to the same block of memory
*p = 'A'; // Input some data
printf("TEST:: %c %d\n", *p, *q); // Everything's ok so far...
free(p); // free() my allocated memory?
sleep(10); // wait
printf("%c\n", *q); // q now points to de-allocated memory
// shouldn't this segfault?
free(q); // *** SEGFAULTS HERE ***
return 0;
}
Output is:
[Linux]$ ./a.out
TEST:: A 65
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000001ac4010 ***
======= Backtrace: =========
...lots of backtrack info...
So I assume that when I free() the first pointer, the memory is considered free()ed, but the data value(s) I wrote in this block of memory are still "there", which is why I can access them via the second pointer?
(I'm not proposing that this is a good idea, I'm trying to understand the logic of the system.)
When you malloc memory, you're given a pointer to some space, and when you free it, you're giving it back to the system. Often, you can still access this memory, but using memory after you have freed it is VERY BAD.
The exact behavior is undefined, but on most systems you can either continue to access the memory, or you get a segfault.
One interesting experiment you can try is to try and malloc more memory after you free'd that pointer. On most systems I've tried, you get the same block back (which is a problem, if you were relying on the data being there in the freed block). Your program would end up using both pointers, but since they point to the same physical data, you'll be overwriting your own data!
The reason for this is that when you malloc data (depending on the malloc implementation of course), malloc first requests a block of data from the operating system (typically much larger than the malloc request), and malloc will give you a segment of that memory. You'll be able to access any part of the memory malloc originally got from the operating system though, since to the operating system, it's all memory your program is internally using. When you make a free, you're telling the malloc system that the memory is free, and can be given back to the program later on.
Writing outside of the malloc area is very dangerous because
It can segfault, depending on your c implementation
You can overwrite metadata structures malloc is relying on, which causes VERY BAD PROBLEMS when you free/malloc more data later on
If you are interested in learning more, I would recommend running your program through valgrind, a leak detector, to get a better picture of what's freed/not freed.
PS: On systems without an OS, you most likely wont get a segfault at all, and you'll be able to wite anywhere willy nilly. The OS is responsible for triggering a segfault (when you write/read to memory you don't have access to, like kernel or protected memory)
If you are interested in learning more, you should try to write your own malloc, and/or read/learn about the memory management operating systems do.
The crash in your code is due to double free. Appendix J.2 of C11 says that behaviour is undefined for example when:
The pointer argument to the free or realloc function does not match a pointer earlier returned by a memory management function, or the space has been deallocated by a call to free or realloc (7.22.3.3, 7.22.3.5).
However it is possible to write code that will crash on Linux just by reading a value from memory that was just freed.
In glibc + Linux there are two different mechanisms of memory allocations. One uses the brk/sbrk to resize the data segment, and the other uses the mmap system call to ask the operating system to give large chunks of memory. The former is used for small allocations, like your 10 characters above, and mmap for large chunks. So you might get a crash by even accessing the memory just after free:
#include <stdio.h>
#include <stdlib.h>
int main(){
char* p = malloc(1024 * 1024);
printf("%d\n", *p);
free(p);
printf("%d\n", *p);
}
And finally, the C11 standard says that the behaviour is undefined even when
The value of a pointer that refers to space deallocated by a call to the free or realloc function is used (7.22.3).
This means that after not only that dereferencing the pointer (*p) has undefined behaviour, but also that it is not safe to use the pointer in any other way, even doing p == NULL has UB. This follows from C11 6.2.4p2 that says:
The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
Hi I have following code
#include <stdio.h>
#include <conio.h>
typedef struct test
{
int a;
int b;
int c[10];
}tester;
typedef struct done
{
tester* t;
int nn;
}doner;
void main()
{
doner d;
d.t = (tester*)malloc(sizeof(d.t));
d.t->a = 10;
d.t->c[0] = 10;
printf("%d\n", d.t->a);
getch();
return;
}
I think the statement:
d.t = (tester*)malloc(sizeof(d.t));
is incorrect it should be:
d.t = (tester*)malloc(sizeof(tester));
but when I run this code it is not crashing please let me the why is this.
The fact that it is not crashing is because it has undefined behavior. The correct code is the second one, but no need for casting.
d.t = malloc(sizeof(tester));
Also, You need to free the malloc'ed pointer.
On many system, the heap is not checked when writing to the malloc'ed buffer, but only when freeing the allocated memory. In such case, you will probably get some kind of crash when you free the memory.
The fact that it's not crashing is a big reason why these sort of memory allocation bugs are so insidious and hard to detect. Your program only allocates the one structure, and doesn't fill it up, so the fact that it runs past the amount of memory allocated to it doesn't affect anything else.
If your program made more use of dynamically-allocated memory, then either the calls to malloc/free would trigger a crash because your structure overwrote the heap's linking metadata, or other parts of the program writing to their own malloc'ed data would overwrite your structure. Either way, not pretty.
Yes, you're right. It should be sizeof(tester), because d.t is just a pointer.
Now if you write sizeof(d.t) you invoke Undefined Behavior which is not a guarantee of crash. The program may run correctly, run incorrectly, crash, or order a pizza. There is no guarantee of what will happen with a program that has undefined behavior, even prior to the construct that leads to it.
As freeing the malloced memory - in this small sample program you don't need to worry about it, because the system will free the memory after your program exits, but in general you should try to free whatever you've allocated so as to avoid memory leaks in larger programs.
By default, the linker asks the OS to allocate 1MiB of (stack) memory for the program at the start-up. Your program doesn't crash because all of the references are still in the same memory (same address space) which was reserved by the OS for your program. Technically you haven't allocated that memory, but as the pointers are still in the valid memory range so your program can access it.
This is just like, in most cases, you can write to d.t->c[10] (although valid indexes are 0-9)
Crashes occur when pointers are used which correspond to memory locations outside the allocated memory. Google Page Fault for detailed understanding, if you are interested.
In the below program, as far as in my knowledge once we allocate some memory then if we are chaging the address from
ptr to ptr++, then when we are calling free with ptr i.e free(ptr).
Then the program should crash.
But in this program works fine.
How it works?
I am using Code::Bocks in Windows XP.
Please help me.
int main()
{
int *ptr;
ptr = malloc(1);
*ptr = 6;
printf("The value at *ptr = %d \n", *ptr);
ptr++; //Now ptr is address has been changed
free(ptr); // Program should crash here
ptr = NULL;
/* *ptr = 5;*/ // This statement is crashing
return 0;
}
The behavior of this program is undefined from the very moment that you store a value through an int* pointing to a single byte. There's no guarantee of a crash.
Specifically, it seems like your free doesn't (maybe can't) check its argument properly. Try running this program with a malloc debugging library.
Absence of a crash does not necessarily mean your code is fine. On another platform, it will probably crash.
BTW: you should rather malloc(sizeof(int))
The program should not necessarily crash, the behavior is undefined.
It works only due to luck; the code is still wrong.
To understand why, one first needs to be familiar with the implementation of the malloc library itself. malloc not only allocates the space it returned for you to use, it also allocates space for its own metadata that it uses to manage the heap (what we call the region of memory managed by malloc). By changing ptr and passing the wrong value to free, the metadata is no longer where free expected it, so the data it's using now is essentially garbage and the heap is corrupted.
This doesn't necessarily mean it'll crash due to say, a segfault, because it doesn't necessarily dereference a bad pointer. The bug still exists and will likely manifest itself in a longer program with more heap usage.
#inlcude <stdio.h>
#inlcude <stdlib.h>
#inlcude <string.h>
int main() {
char *buff = (char*)malloc(sizeof(char) * 5);
char *str = "abcdefghijklmnopqrstuvwxyz";
memcpy (buff, str, strlen(str));
while(*buff) {
printf("%c" , *buff++);
}
printf("\n");
return 0;
}
this code prints the whole string "abc...xyz". but "buff" has no enough memory to hold that string. how memcpy() works? does it use realloc() ?
Your code has Undefined Behavior. To answer your question, NO, memcpy doesn't use realloc.
sizeof(buf) should be adequate to accomodate strlen(str). Anything less is a crash.
The output might be printed as it's a small program, but in real big code it will cause hard to debug errors. Change your code to,
const char* const str = "abcdefghijklmnopqrstuvwxyz";
char* const buff = (char*)malloc(strlen(str) + 1);
Also, don't do *buff++ because you will loose the memory record (what you allocated). After malloc() one should do free(buff) once the memory usage is over, else it's a memory leak.
You might be getting the whole string printed out, but it is not safe and you are writing to and reading from unallocated memory. This produces Undefined Behavior.
memcpy does not do any memory allocation. It simply reads from and writes to the locations you provide. It doesn't check that it is alright to do so, and in this case you're lucky if your program doesn't crash.
how memcpy() works?
Because you've invoked undefined behavior. Undefined behavior may work exactly as you expect, and it may do something completely different. It may even differ between different runs of the same program. It could also format your hard disk and still be compliant with the standard (Though of course that's unlikely :P )
Undefined behavior means that the behavior is literally not defined to do anything. Anything is valid, including the behavior you're seeing. Note that if you try to free that memory the C runtime of your target platform will probably complain. ;)
No memcpy does not use malloc. As you suspected, you are writing off the end of of buff. In your simple example, that does no apparent harm, but it is bad. Here are some of the things that could go wrong in a "real" program:
You might scribble on something allocated in the memory following your buff leading to subtle (or not so subtle) bugs later on.
You might scribble on headers used internally by malloc and free, leading to crashes or other problems on your next call to those functions.
You might end up writing to an address that has not been allocated to your process, in which case your program will immediately crash. (I suspect this is what you were expecting.)
There are malloc implementations that put unmapped guard pages around allocated memory to (usually) cause the program to crash in cases like this. Other implementations will detect this, but only on your next call to malloc or free (or when you call a special function to check the heap).
I have seen some differences in the result of the following code:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void)
{
char* ptr;
ptr = (char*)malloc(sizeof(char) * 12);
strcpy(ptr, "Hello World");
printf("%s\n", ptr);
printf("FREEING ?\n");
free(ptr);
printf("%s\n", ptr);
}
Let me explain:
In the third call to printf depending the OS I get different results, gargabge caracters in Windows, nothing in Linux and in A Unix system "Hello World" is printed.
Is there a way to check the status of the pointer to know when memory has been freed?
I think this mechanism of print can not be trusted all the times.
Thnaks.
Greetings.
Using a pointer after it has been freed results in undefined behavior.
That means the program may print garbage, print the former contents of the string, erase your hard drive, or make monkeys fly out of your bottom, and still be in compliance with the C standard.
There's no way to look at a pointer and "know when memory has been freed". It's up to you as a programmer to keep track.
If you call free(), the memory will have been freed when that function returns. That doesn't mean that the memory will be overwritten immediately, but it's nevertheless unsafe to use any pointer on which you've called free().
It's a good idea to always assign nil to a pointer variable once you've freed it. That way, you know that non-nil pointers are safe to use.
Simple ansewr: you can't check if a pointer has been freed already in C. Different behaviors are probably due to different compilers, as using a pointer after freeing it is undefined you can get all sorts of behavior (including a SEGFAULT and program termination).
If you want to check if you use free property and your program is memory leak free, then use a tool like Valgrind.