Reputation: 21
While studying pointers I found that if I allocate memory for a 2 digit int I can give that int a higher value. Can someone explain me why it works like that and how to work around it?
Here is the code:
int *p;
p = (int *) malloc(2*sizeof(int));
p = 123456;
Upvotes: 1
Views: 219
Reputation: 134396
First of all, Please see this discussion on why not to cast the return value of malloc()
and family in C
..
That said, here, you're just overwriting the pointer returned by malloc()
. Don't do that. It will cause memory leak. Also, if you try to dereference this pointer later, you may face undefined behavior, as there is no guarantee that this pointer points to a valid memory location. Accessing invalid memory leads to UB.
Finally, to address
I allocate memory for a 2 digit int [...]
let me tell you, you are allocating memory to hold two integers, not a two digit integer. Also, to store the integer values into the memory area pointed by the pointer, you need to dereference the pointer, like *p
and store (assign) the value there, like *p=12345;
.
malloc()
allocates memory of the size of bytes passed as it's argument. Check the sizeof(int)
(and 2*sizeof(int),
if you want) to make it more clear.
Regarding this, quoting C11
, chapter
void *malloc(size_t size);
The
malloc
function allocates space for an object whose size is specified bysize
[...]
So, here, malloc()
returns a pointer with the size of two integers (i.e., capable of holding two integer values), not two digits or bytes.
Also, it's always a good practice to check the success of malloc()
before using the returned pointer to avoid the possible UB by dereferencing NULL in case of malloc()
failure.
Upvotes: 4
Reputation: 60037
you do not need the cast in the first place
You are allocated memory for two integers - typically 32 bits each
Perhaps reread the book
Upvotes: -1
Reputation: 727067
if i allocate memory for a 2 digit int i can give that int a higher value.
No, you cannot. You have allocated memory for two int
s, with full int
range. Standard guarantees at least five digits (215-1), but on most modern systems you are safe with eight digits (231-1).
Back to your question, there is no way in C to ensure that your program does not write past the end of the memory that it allocates. It is the responsibility of your program to not do that, including any checks it must perform in order to catch potentially unsafe access.
This is called undefined behavior. The system may crash when you access memory past the end of the allocated area, but it does not have to.
Upvotes: 2
Reputation: 500913
allocate memory for a 2 digit int
malloc(2*sizeof(int))
allocates memory for two integers, not for a single two-digit integer.
Upvotes: 0