I'm slowly getting the hang of pointers. But there are still some questions I have.
Is it possible to cause memory leaks when using pointer arithmetic because you are shifting the actual position of where the pointer is pointing to?
I mean, if say I count upwards to copy a string char by char, would I need to count down so C "knows" where the pointer used to point to?
Thanks Frank
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -
You can perform a limited number of arithmetic operations on pointers. These operations are: Increment and decrement. Addition and subtraction.
When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.
Differences between delete and free() The delete operator is used to delete the pointer, which is either allocated using new operator or a NULL pointer, whereas the free() function is used to delete the pointer that is either allocated using malloc(), calloc() or realloc() function or NULL pointer.
A memory leak is possible when using malloc()
or similar functions and not calling free()
when it's needed. free()
should always be called with the pointer returned by malloc()
, so yes if you do something like this:
int* ptr = malloc(sizeof(int));
free(ptr + 1);
causes undefined behaviour. Could be a memory leak, maybe a segmentation fault, anything is possible.
Memory is allocated on the heap. A pointer is just that, a pointer to the location in memory. You need to know the address of the start of the allocated memory in order to free it later.
This is because the information about allocated memory (e.g. how much was allocated) needs to be remembered by the memory management system so it knows how much to free later, and to prevent it from allocating the same block to another malloc call. The start address of the memory is what identifies it.
If you want to fiddle with the pointer, take a copy of it and don't modify the original pointer.
int *x = malloc(...);
int *y = x;
... pointer arithmetic with y
free(x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With