Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Beginner question: Pointer arithmetic > cleaning up once you are done

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

like image 639
Frank Vilea Avatar asked May 11 '11 12:05

Frank Vilea


People also ask

What is C pointer arithmetic?

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 -

What arithmetic operations can be performed on pointers?

You can perform a limited number of arithmetic operations on pointers. These operations are: Increment and decrement. Addition and subtraction.

What is pointer arithmetic in C with example?

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.

Does Free Get rid of the pointer?

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.


2 Answers

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.

like image 96
insumity Avatar answered Sep 30 '22 00:09

insumity


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);
like image 44
Joe Avatar answered Sep 29 '22 23:09

Joe