• Understanding Quick Sort for coding interviews
  • Understanding Insertion Sort for coding interviews
  • Understanding Bubble Sort for coding interviews
  • Understanding selection sort for coding interviews
  • Generate binary numbers using a queue

A CODERS JOURNEY

Top 20 C pointer mistakes and how to fix them

After I graduated college with a BS in Electrical Engineering, I thought that was the last time I was going to program in “C”. I could not have been more wrong. Throughout various points in my career, I’ve encountered and wrangled with a decent amount of “C” code either due to legacy or portability reasons.

Pointers are the most complicated and fundamental part of the C Programming language. Most of the mistakes I’ve made in school assignments and production code is in handling pointers. So here is my attempt to catalog some of the common and not so common mistakes – something I ca refer back to the next time I have to write production code in C. Hope it helps you as well.

Mistake # 1: Omitting the pointer “*” character when declaring multiple pointers in same declaration

Consider the following declaration:

It declares an integer pointer p1 and an integer p2 . More often than not, the intent is to declare two integer pointers.

In the test code below, the last line will result in a compile error “Error C2440 ‘=’: cannot convert from ‘int *’ to ‘int’ ”

This is a pretty basic mistake that most modern compilers will catch.

Recommended Fix:

Use the following declaration to declare two pointers of the same type:

Alternatively, use a typedef – for example,

and then, use this type when declaraing pointers:

Mistake # 2: Using uninitialized pointers

The usage of an uninitialized pointer typically results in program crashes if the pointer accesses memory it is not allowed to.

Consider the code below:

On debug builds in Visual Studio, you’ll first get the following error:

followed by:

0xcc is microsoft’s debug mode marker for uninitialized stack memory.

On release builds, you’ll encounter a runtime crash on the line :printf(“%d”, n);

Recommended Fix: Always initialize pointers to a valid value.

Mistake # 3: Assigning a pointer to an uninitialized variable

This is more dangerous, IMHO, than an uninitialized pointer.In this case, unlike an uninitialized pointer, you won’t get a crash. Instead it can lead to serious logic errors in your code.

On debug builds, it’ll result in a large negative number like “-858993460”. In VC++, the result will be 0 but that is not guaranteed by the C standard .  More specifically item 1652 in the referenced doc states that If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

Deceptively simple – do not assign pointers to uninitialized variables.

Mistake # 4: Assigning value to pointer variables

Another one of the novice errors where the IDE/compiler will most likely bail you out. Consider the code:

The problem is that p1 can contain an address of an int and not the int value itself. You’ll get a compiler error:

Assign the address of the integer variable to the pointer .

Mistake # 5: Incorrect syntax for incrementing dereferenced pointer values

If the intent is to increment a variable pointed to by a pointer, the following code fails to achieve that.

In fact, p1 now points to an undefined memory location. When you run this code, you get the following output with the first line corresponding to the value at the address p1 points to.

Recommended Fix: To increment a dereferenced pointer, use : (*p1)++;

Mistake # 6: Trying to deallocate stack memory using free()

Consider the code below where variable m is allocated on the stack.

Attempting to free memory on the stack using the free() function throws an access violation.

Memory on the stack(non-pointer variables) is done implicitly by the system. It is illegal to get memory from the stack and return it to the heap.

Recommended Fix: Use free() to deallocate memory that has been previously allocated by malloc() or one of its variants. Always remember where the memory came from – stack or heap 🙂

Mistake # 7: Dereferncing the value of a pointer after it has been freed

Consider the following code – we allocate an integre pointer, use it , free the memory associated with the pointer and then try to use the pointer again. This’ll end in undefined behavior – maybe crashes depending on the state of the system/platform.

Never use a pointer after it has been freed. A good practice is to set the pointer to NULL after it has been freed such that any attempt to use it again is caught by an access violation.A crash during development is better than undefined behavior after release 🙂

Mistake # 8 : Double free()

Calling free() on a block of memory twice will lead to heap corruption. For example, the following code results in an unhandled exception indicating heap corruption using MS VC++:

This type of issue caused a security vulnerability in zlib which you can read about here .

Do not free the same block of memory twice! Simply assign NULL to a pointer after it has been freed. Subsequent attempts to free a null pointer will be ignored by most heap managers.

Mistake # 9 : Not using sizeof() operator with malloc

If you’re implementing something in C in this day and age, most likely you’re doing it with platform portability in mind. The size of data types can vary across different platform architectures. If you write something like malloc(2), you might have trouble porting it across platforms.

Recommended Fix: Always use sizeof(type) with malloc – for example:

Mistake # 10 : Using a pointer and sizeof() to determine the size of an array

In the code below, sizeof(arr) will correctly determine the size of the char array but a pointer to the array won’t. The type of *cp is const char, which can only have a size of 1, whereas the type of arr is different: array of const char.

Recommended Fix: Never use sizeof on a pointer to an array to determine the size of the array.

Mistake # 11 : Creating garbage objects using C pointers

You need a pointer to a memory location to free / deallocate that memory. If you re-assign a pointer and there is no other pointer pointing to that memory block, you cannot deallocate that previous memory block. This causes a memory leak.

“Memory block 1” is not inaccessible because we don’t have a pointer to it. Without having a pointer to a memory block, we cannot call free() on a block and we’ve created a garbage object in that block – in other words, we leaked memory.

In general, it’s not a good idea to recycle pointer variables. Use new pointer variables where possible and remember to set a pointer variable to NULL right after it has been freed.

Mistake # 12 : Not Understanding the difference between shallow copy and deep copy

Given two pointers p and q, the assignment p = q does not copy the block of memory pointed to by q into a block of memory pointed to by p; instead it assigns memory addresses ( so that both p and q point to the same memory location; changing the value of that memory location affects both pointers).

So what just happened?

In the shallow copy case, af1 and af2 both points to the same memory location. Any change to the memory location via af2 is reflected when af1 is used.

In the deep copy case, when we modify af3 (which points to an entirely different memory block than af1), the memory block pointed by af1 is not affected.

Mistake # 13 : Freeing a memory block shared by two pointers using one of the pointers and subsequently trying to use the other pointer

In the code below,. str1 and str2 points to the same memory block – so when str1 is freed, essentially the memory block pointed to by str2 is freed. Any attempt to use str2 after str1 has been freed will cause undefined behavior. In the case of the program below – it’ll print some garbage value.

There’s really no good way around this in C except to use static analyzers. If you’re in C++, you can use shared_pointers – but use caution as advised in the linked article. . There’s also a good discussion on Stackoverflow on this topic.

Mistake # 14 : Trying to access memory locations not allocated by your code

If you have allocated a block of n objects, do not try to access objects beyond this block ( which includes any objects in locations p+n and beyond)

The statement  doubleVals[SIZE] = 25.99  is essentially writing over memory it does not own – which can cause undefined behavior in programs.

Always be aware of the bounds of memory allocated by your code and operate within those safe limits.

Mistake # 15 : Off by one errors when operating on C pointers

Given a block of memory of SIZE objects pointed to by p, the last object in the block can be retrieved by using another pointer q and setting it to (p+SIZE-1) instead of (p+SIZE).

The first print statement incorrectly prints “0” while the last element is “9”. The second print statement fixes it by accessing the last element at (q + SIZE – 1)

Carefully apply the “off by one error” rules that you learnt for array access to pointers.

Mistake # 16 : Mismatching the type of pointer and type of underlying data

Always use the appropriate pointer type for the data. Consider the code below where a pointer to an integer is assigned to a short:

Notice that it appears that the first hexadecimal digit stored at address 100 is 7 or f, depending on whether it is displayed as an integer or as a short. This apparent contradiction is an artifact of executing this sequence on a little endian machine.If we treat this as a short number and only use the first two bytes, then we get the short value of –1. If we treat this as an integer and use all four bytes, then we get 2,147,483,647.

Always use the correct pointer type for a specific data type – int* for int , double* for double etc.

Mistake # 17 : Comparing two pointers to determine object equality

Often we want to compare if the contents of two objects are same – for example check if two strings are equal.

In the code below, clearly the intent was to check if both strings are “Thunderbird”. But, we ended up comparing the memory addresses with the statement “str1 == str2”. Here str1 and str2 are essentially pointers to different memory addresses which holds the same string.

The code can be made to work as intended, i.e., compare string contents by making the following changes:

Always remember to compare the contents of the memory location pointed to by pointers instead of comparing the address of pointer themselves.

Mistake # 18 : Thinking that C arrays are pointers

While C pointers and Arrays can be used interchangeably in most situations, they are not quite the same. Here’s an example of where it is a recipe for access violation.

In File2.cpp, global_array is declared as an pointer but defined as an array in File1.cpp. At a high level, the compile generates different code for array indexing and access via pointer.

Change the declaration so it does match the definition, like:

Note: A detailed discussion is beyond the scope of this article. The best explanation of this issue I found was in the section, “Chapter 4. The Shocking Truth: C Arrays and Pointers Are NOT the Same!” in Deep C Secrets . It’s a fantastic book if you really want to become an expert C programmer – highly recommended.

Mistake # 19 : Not clearing out sensitive heap data managed through pointers

When an application terminates, most operating systems do not zero out or erase the heap memory that was in use by your application. The memory blocks used by your application can be allocated to another program, which can use the contents of non-zeroed out memory blocks. Just imagine you asked for a security question from the user and stored it in heap memory – it’s always a good idea to erase that memory block contents before returning the memory to the Operating System via free().

Mistake # 20 : Not taking time to understand C function pointers

Functions pointers are used extensively in many large scale production system. It’s also critical to understand more advanced concepts like callbacks, events in Win32 or lambdas in standard C++.

Here’s an example of function pointer in linux kernel:

If code like this makes your head swivel, no sweat – mine did too when i started my career. 🙂

The problem is that most college level C courses seldom does any deep exploration of function pointers, whereas once you’re in industry, it’s all over the place. Here is a good book that has an in-depth treatment of C function pointers : Understanding and Using C Pointers .

Final Thoughts

C is one of the oldest languages in use today. Pointers forms the heart and soul of C. Pointers are not only useful for writing production quality code but also in school for understanding the concepts behind self referential data structures like linked list and binary trees. Even if you are working in a high level language like Java or C#, an object is essentially a pointer. So, study pointers well because they keep showing up in coding interviews and tech screens – I wouldn’t be surprised if you get a question similar to the code snippets in this article and asked “what’s wrong with this piece of C code?”.

Good luck !

  • 35 things I learnt at Game Developer Conference (GDC) 2018
  • System Design Interview Concepts – CAP Theorem
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C.

In this article, we will discuss C pointers in detail, their types, uses, advantages, and disadvantages with examples.

What is a Pointer in C?

A pointer is defined as a derived data type that can store the address of other C variables or a memory location. We can access and manipulate the data stored in that memory location using pointers.

As the pointers in C store the memory addresses, their size is independent of the type of data they are pointing to. This size of pointers in C only depends on the system architecture.

Syntax of C Pointers

The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration.

  • ptr is the name of the pointer.
  • datatype is the type of data it is pointing to.

The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures, etc.

How to Use Pointers?

The use of pointers in C can be divided into three steps:

  • Pointer Declaration
  • Pointer Initialization
  • Pointer Dereferencing

1. Pointer Declaration

In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name.

The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.

2. Pointer Initialization

Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( &: ampersand ) addressof operator to get the memory address of a variable and then store it in the pointer variable.

We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time.

Note: It is recommended that the pointers should always be initialized to some value before starting using it. Otherwise, it may lead to number of errors.

3. Pointer Dereferencing

Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration.

dereferencing a pointer in c

Dereferencing a Pointer in C

C Pointer Example

Types of pointers in c.

Pointers in C can be classified into many different types based on the parameter on which we are defining their types. If we consider the type of variable stored in the memory location pointed by the pointer, then the pointers can be classified into the following types:

1. Integer Pointers

As the name suggests, these are the pointers that point to the integer values.

These pointers are pronounced as Pointer to Integer.

Similarly, a pointer can point to any primitive data type. It can point also point to derived data types such as arrays and user-defined data types such as structures.

2. Array Pointer

Pointers and Array are closely related to each other. Even the array name is the pointer to its first element. They are also known as Pointer to Arrays . We can create a pointer to an array using the given syntax.

Pointer to Arrays exhibits some interesting properties which we discussed later in this article.

3. Structure Pointer

The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can be declared in the same way as we declare the other primitive data types.

In C, structure pointers are used in data structures such as linked lists, trees, etc.

4. Function Pointers

Function pointers point to the functions. They are different from the rest of the pointers in the sense that instead of pointing to the data, they point to the code. Let’s consider a function prototype – int func (int, char) , the function pointer for this function will be

Note: The syntax of the function pointers changes according to the function prototype.

5. Double Pointers

In C language, we can define a pointer that stores the memory address of another pointer. Such pointers are called double-pointers or pointers-to-pointer . Instead of pointing to a data value, they point to another pointer.

Dereferencing Double Pointer

Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3, ****ptr4, ******ptr5 and so on.

6. NULL Pointer

The Null Pointers are those pointers that do not point to any memory location. They can be created by assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.

It is said to be good practice to assign NULL to the pointers currently not in use.

7. Void Pointer

The Void pointers in C are the pointers of type void. It means that they do not have any associated data type. They are also called generic pointers as they can point to any type and can be typecasted to any type.

One of the main properties of void pointers is that they cannot be dereferenced.

8. Wild Pointers

The Wild Pointers are pointers that have not been initialized with something yet. These types of C-pointers can cause problems in our programs and can eventually cause them to crash. If values is updated using wild pointers, they could cause data abort or data corruption.

9. Constant Pointers

In constant pointers, the memory address stored inside the pointer is constant and cannot be modified once it is defined. It will always point to the same memory address.

10. Pointer to Constant

The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here we can only access the data pointed by the pointer, but cannot modify it. Although, we can change the address stored in the pointer to constant.

Other Types of Pointers in C:

There are also the following types of pointers available to use in C apart from those specified above:

  • Far pointer : A far pointer is typically 32-bit that can access memory outside the current segment.
  • Dangling pointer : A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer.
  • Huge pointer : A huge pointer is 32-bit long containing segment address and offset address.
  • Complex pointer: Pointers with multiple levels of indirection.
  • Near pointer : Near pointer is used to store 16-bit addresses means within the current segment on a 16-bit machine.
  • Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment register as possible.
  • File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

Size of Pointers in C

The size of the pointers in C is equal for every pointer type. The size of the pointer does not depend on the type it is pointing to. It only depends on the operating system and CPU architecture. The size of pointers in C is 

  • 8 bytes for a 64-bit System
  • 4 bytes for a 32-bit System

The reason for the same size is that the pointers store the memory addresses, no matter what type they are. As the space required to store the addresses of the different memory locations is the same, the memory required by one pointer type will be equal to the memory required by other pointer types.

How to find the size of pointers in C?

We can find the size of pointers using the sizeof operator as shown in the following program:

Example: C Program to find the size of different pointer types.

As we can see, no matter what the type of pointer it is, the size of each and every pointer is the same.

Now, one may wonder that if the size of all the pointers is the same, then why do we need to declare the pointer type in the declaration? The type declaration is needed in the pointer for dereferencing and pointer arithmetic purposes.

C Pointer Arithmetic

The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on a pointer. It is slightly different from the ones that we generally use for mathematical calculations as only a limited set of operations can be performed on pointers. These operations include:

  • Increment in a Pointer
  • Decrement in a Pointer
  • Addition of integer to a pointer
  • Subtraction of integer to a pointer
  • Subtracting two pointers of the same type
  • Comparison of pointers of the same type.
  • Assignment of pointers of the same type.

C Pointers and Arrays

In C programming language, pointers and arrays are closely related. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably.

If we assign this value to a non-constant pointer of the same type, then we can access the elements of the array using this pointer.

Example 1: Accessing Array Elements using Pointer with Array Subscript

relationship between array and pointer

Not only that, as the array elements are stored continuously, we can pointer arithmetic operations such as increment, decrement, addition, and subtraction of integers on pointer to move between array elements.

Example 2: Accessing Array Elements using Pointer Arithmetic

accessing array elements using pointer arithmetic

This concept is not limited to the one-dimensional array, we can refer to a multidimensional array element as well using pointers.

To know more about pointers to an array, refer to this article – Pointer to an Array

Uses of Pointers in C

The C pointer is a very powerful tool that is widely used in C programming to perform various useful operations. It is used to achieve the following functionalities in C:

  • Pass Arguments by Reference
  • Accessing Array Elements
  • Return Multiple Values from Function
  • Dynamic Memory Allocation
  • Implementing Data Structures
  • In System-Level Programming where memory addresses are useful.
  • In locating the exact value at some memory location.
  • To avoid compiler confusion for the same variable name.
  • To use in Control Tables.

Advantages of Pointers

Following are the major advantages of pointers in C:

  • Pointers are used for dynamic memory allocation and deallocation.
  • An Array or a structure can be accessed efficiently with pointers
  • Pointers are useful for accessing memory locations.
  • Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
  • Pointers reduce the length of the program and its execution time as well.

Disadvantages of Pointers

Pointers are vulnerable to errors and have following disadvantages:

  • Memory corruption can occur if an incorrect value is provided to pointers.
  • Pointers are a little bit complex to understand.
  • Pointers are majorly responsible for memory leaks in C .
  • Pointers are comparatively slower than variables in C.
  • Uninitialized pointers might cause a segmentation fault.

In conclusion, pointers in C are very capable tools and provide C language with its distinguishing features, such as low-level memory access, referencing, etc. But as powerful as they are, they should be used with responsibility as they are one of the most vulnerable parts of the language.

FAQs on Pointers in C

Q1. define pointers..

Pointers are the variables that can store the memory address of another variable.

Q2. What is the difference between a constant pointer and a pointer to a constant?

A constant pointer points to the fixed memory location, i.e. we cannot change the memory address stored inside the constant pointer. On the other hand, the pointer to a constant point to the memory with a constant value.

Q3. What is pointer to pointer?

A pointer to a pointer (also known as a double pointer) stores the address of another pointer.

Q4. Does pointer size depends on its type?

No, the pointer size does not depend upon its type. It only depends on the operating system and CPU architecture.

Q5. What are the differences between an array and a pointer?

The following table list the differences between an array and a pointer : Pointer Array A pointer is a derived data type that can store the address of other variables. An array is a homogeneous collection of items of any type such as int, char, etc. Pointers are allocated at run time. Arrays are allocated at runtime. The pointer is a single variable. An array is a collection of variables of the same type. Dynamic in Nature Static in Nature.

Q6. Why do we need to specify the type in the pointer declaration?

Type specification in pointer declaration helps the compiler in dereferencing and pointer arithmetic operations.
  • Quiz on Pointer Basics
  • Quiz on Advanced Pointer

Please Login to comment...

Similar reads.

  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

DEV Community

DEV Community

AbdulKarim

Posted on Oct 29, 2023

How C-Pointers Works: A Step-by-Step Beginner's Tutorial

In this comprehensive C Pointers tutorial, my primary goal is to guide you through the fundamentals of C pointers from the ground up. By the end of this tutorial, you will have gained an in-depth understanding of the following fundamental topics:

  • What is a Pointer?
  • How Data is Stored in Memory?
  • Storing Memory Addresses using Pointers

Accessing Data through Pointers

  • Pointer Arithmetic
  • Pointer to Pointer (Double Pointers)
  • Passing Pointers as Function Arguments

Arrays of Pointers

Null pointers, prerequisite:.

To grasp pointers effectively, you should be comfortable with basic C programming concepts, including variables, data types, functions, loops, and conditional statements. This familiarity with C programming forms the foundation for understanding how pointers work within the language. Once you have a solid grasp of these fundamental concepts, you can confidently delve into the intricacies of C pointers.

What is a pointer?

A pointer serves as a reference that holds the memory location of another variable. This memory address allows us to access the value stored at that location in the memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory

Pointers can be a challenging concept for beginners to grasp, but in this tutorial, I'll explain them using real-life analogies to make the concept clearer. However, Before delving into pointers and their workings, it's important to understand the concept of a memory address.

A memory address is a unique identifier that points to a specific location in a computer's memory. Think of it like a street address for data stored in your computer's RAM (Random Access Memory). Just as a street address tells you where a particular house is located in the physical world, a memory address tells the computer where a specific piece of information or data is stored in its memory.

Take a look at the image below for a better understanding:

Block of memory

In this illustration, each block represents one byte of memory. It's important to note that every byte of memory has a unique address. To make it easier to understand, I've represented the addresses in decimal notation, but computers actually store these addresses using hexadecimal values. Hexadecimal is a base-16 numbering system commonly used in computing to represent memory addresses and other low-level data. It's essential to be aware of this representation when working with memory-related concepts in computer programming

How data is stored in the memory:

Every piece of data in your computer, whether it's a number, a character, or a program instruction, is stored at a specific memory address. The amount of space reserved for each data type can vary, and it is typically measured in bytes (where 1 byte equals 8 bits, with each bit representing either 0 or 1). The specific sizes of data types also depend on the computer architecture you are using. For instance, on most 64-bit Linux machines, you'll find the following typical sizes for common data types: char = 1 byte int = 4 bytes float = 4 bytes double = 8 bytes These sizes define how much memory each data type occupies and are crucial for memory management and efficient data representation in computer systems.

You can use the sizeof operator to determine the size of data types on your computer. example:

In this example: sizeof(char) returns the size of the char data type in bytes. sizeof(int) returns the size of the int data type in bytes. sizeof(float) returns the size of the float data type in bytes. sizeof(double) returns the size of the double data type in bytes. When you run this code, it will print the sizes of these data types on your specific computer, allowing you to see the actual sizes used by your system.

When you declare a variable, the computer allocates a specific amount of memory space corresponding to the chosen data type. For instance, when you declare a variable of type char, the computer reserves 1 byte of memory because the size of the 'char' data type is conventionally 1 byte.

address of char n

In this example, we declare a variable n of type char without assigning it a specific value. The memory address allocated for the n variable is 106 . This address, 106 , is where the computer will store the char variable n, but since we haven't assigned it a value yet, the content of this memory location may initially contain an unpredictable or uninitialized value.

When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n. When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n.

address of cahr n = c

As mentioned earlier, a byte can only store numerical values. When we store the letter 'C' in a byte, the byte actually holds the ASCII code for 'C,' which is 67. In computer memory, characters are represented using their corresponding ASCII codes. So, in memory, the character 'C' is stored as the numerical value 67. Here's how it looks in memory

Ascii code of c

Since integers are typically stored within four bytes of memory, let's consider the same example with an int variable. In this scenario, the memory structure would appear as follows:

add. of int t

In this example, the memory address where the variable t is stored is 121. An int variable like “t” typically uses four consecutive memory addresses, such as 121, 122, 123, and 124. The starting address, in this case, 121, represents the location of the first byte of the int, and the subsequent addresses sequentially represent the following bytes that collectively store the complete int value.

If you want to know the memory address of a variable in a program, you can use the 'address of' unary operator, often denoted as the '&' operator. This operator allows you to access the specific memory location where a variable is stored.

When you run the following program on your computer: It will provide you with specific memory addresses for the variables c and n. However, each time you rerun the program, it might allocate new memory addresses for these variables. It's important to understand that while you can determine the memory address of a variable using the & operator, the exact memory location where a variable is stored is typically managed by the system and the compiler. As a programmer, you cannot directly control or assign a specific memory location for a variable. Instead, memory allocation and management are tasks handled by the system and the compiler.

Storing memory address using pointers

As mentioned earlier, a pointer is a variable that stores the memory address of another variable. This memory address allows us to access the value stored at that location in memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory.

Now, let's begin by declaring and initializing pointers. This step is essential because it sets up the pointer to hold a specific memory address, enabling us to interact with the data stored at that location.

Declaring Pointers: To declare a pointer, you specify the data type it points to, followed by an asterisk (*), and then the pointer's name. For example:

Here, we've declared a pointer named ptr that can point to integers.

Memory of Declaring an integer pointer

The size of pointers on 64-bit systems is usually 8 bytes (64 bits). To determine the pointer size on your system, you can use the sizeof operator:

Initializing Pointers: Once you've declared a pointer, you typically initialize it with the memory address it should point to. Once again, To obtain the memory address of a variable, you can employ the address-of operator (&). For instance:

In this program:

We declare an integer variable x and initialize it with the value 10. This line creates a variable x in memory and assigns the value 10 to it.

ptr

We declare an integer pointer ptr using the int *ptr syntax. This line tells the compiler that ptr will be used to store the memory address of an integer variable.

pointrt to ptr

We initialize the pointer ptr with the memory address of the variable x . This is achieved with the line ptr = &x; . The & operator retrieves the memory address of x, and this address is stored in the pointer ptr .

address of variable x

Dereferencing Pointers: To access the data that a pointer is pointing to, you need to dereference the pointer. Dereferencing a pointer means accessing the value stored at the memory address that the pointer points to. In C, you can think of pointers as variables that store memory addresses rather than actual values. To get the actual value (data) stored at that memory address, you need to dereference the pointer.

Dereferencing is done using the asterisk (*) operator. Here's an example:

It looks like this in the memory: int x = 10; variable 'x' stores the value 10:

var X

int *ptr = &x; Now, the pointer 'ptr' point to the address of 'x':

Pointer to X

int value = *ptr; Dereference 'ptr' to get the value stored at the address it points to:

pointer value is 10

Reading and Modifying Data: Pointers allow you to not only read but also modify data indirectly:

Note: The asterisk is a versatile symbol with different meanings depending on where it's used in your C program, for example: Declaration: When used during variable declaration, the asterisk (*) indicates that a variable is a pointer to a specific data type. For example: int *ptr; declares 'ptr' as a pointer to an integer.

Dereferencing: Inside your code, the asterisk (*) in front of a pointer variable is used to access the value stored at the memory address pointed to by the pointer. For example: int value = *ptr; retrieves the value at the address 'ptr' points to.

Pointer Arithmetic:

Pointer arithmetic is the practice of performing mathematical operations on pointers in C. This allows you to navigate through arrays, structures, and dynamically allocated memory. You can increment or decrement pointers, add or subtract integers from them, and compare them. It's a powerful tool for efficient data manipulation, but it should be used carefully to avoid memory-related issues.

Incrementing a Pointer:

Now, this program is how it looks in the memory: int arr[4] = {10, 20, 30, 40};

int arr

This behavior is a key aspect of pointer arithmetic. When you add an integer to a pointer, it moves to the memory location of the element at the specified index, allowing you to efficiently access and manipulate elements within the array. It's worth noting that you can use pointer arithmetic to access elements in any position within the array, making it a powerful technique for working with arrays of data. Now, let's print the memory addresses of the elements in the array from our previous program.

If you observe the last two digits of the first address is 40, and the second one is 44. You might be wondering why it's not 40 and 41. This is because we're working with an integer array, and in most systems, the size of an int data type is 4 bytes. Therefore, the addresses are incremented in steps of 4. The first address shows 40, the second 44, and the third one 48

Decrementing a Pointer Decrement (--) a pointer variable, which makes it point to the previous element in an array. For example, ptr-- moves it to the previous one. For example:

Explanation:

We have an integer array arr with 5 elements, and we initialize a pointer ptr to point to the fourth element (value 40) using &arr[3].

Then, we decrement the pointer ptr by one with the statement ptr--. This moves the pointer to the previous memory location, which now points to the third element (value 30).

Finally, we print the value pointed to by the decremented pointer using *ptr, which gives us the value 30.

In this program, we demonstrate how decrementing a pointer moves it to the previous memory location in the array, allowing you to access and manipulate the previous element.

Pointer to pointer

Pointers to pointers, or double pointers, are variables that store the address of another pointer. In essence, they add another level of indirection. These are commonly used when you need to modify the pointer itself or work with multi-dimensional arrays.

To declare and initialize a pointer to a pointer, you need to add an extra asterisk (*) compared to a regular pointer. Let's go through an example:

In this example, ptr2 is a pointer to a pointer. It points to the memory location where the address of x is stored (which is ptr1 ).

pointer to poiter

The below program will show you how to print the value of x through pointer to pointer

In this program, we first explain that it prints the value of x using a regular variable, a pointer, and a pointer to a pointer. We then print the memory addresses of x , ptr1 , and ptr2 .

Passing Pointers as Function Arguments:

In C, you can pass pointers as function arguments. This allows you to manipulate the original data directly, as opposed to working with a copy of the data, as you would with regular variables. Here's how it works:

How to Declare and Define Functions that Take Pointer Arguments: In your function declaration and definition, you specify that you're passing a pointer by using the * operator after the data type. For example:

In the above function, we declare ptr as a pointer to an integer. This means it can store the memory address of an integer variable.

Why Would You Pass Pointers to Functions?

Passing pointers to functions allows you to:

  • Modify the original data directly within the function.
  • Avoid making a copy of the data, which can be more memory-efficient.
  • Share data between different parts of your program efficiently.

This concept is especially important when working with large data structures or when you need to return multiple values from a function.

Call by Value vs. Call by Reference:

Understanding how data is passed to functions is crucial when working with pointers. there are two common ways that data can be passed to functions: call by value and call by reference.

Call by Value:

When you pass data by value, a copy of the original data is created inside the function. Any modifications to this copy do not affect the original data outside of the function. This is the default behavior for most data types when you don't use pointers.

Call by Reference (Using Pointers):

When you pass data by reference, you're actually passing a pointer to the original data's memory location. This means any changes made within the function will directly affect the original data outside the function. This is achieved by passing pointers as function arguments, making it call by reference. Using pointers as function arguments allows you to achieve call by reference behavior, which is particularly useful when you want to modify the original data inside a function and have those changes reflected outside the function.

Let's dive into some code examples to illustrate how pointers work as function arguments. We'll start with a simple example to demonstrate passing a pointer to a function and modifying the original data.

Consider this example:

In this code, we define a function modifyValue that takes a pointer to an integer. We pass the address of the variable num to this function, and it doubles the value stored in num directly.

This is a simple demonstration of passing a pointer to modify a variable's value. Pointers allow you to work with the original data efficiently.

An array of pointers is essentially an array where each element is a pointer. These pointers can point to different data types (int, char, etc.), providing flexibility and efficiency in managing memory.

How to Declare an Array of Pointers? To declare an array of pointers, you specify the type of data the pointers will point to, followed by square brackets to indicate it's an array, and then the variable name. For example:

Initializing an Array of Pointers You can initialize an array of pointers to each element to point to a specific value, For example:

How to Access Elements Through an Array of Pointers? To access elements through an array of pointers, you can use the pointer notation. For example:

This program demonstrates how to access and print the values pointed to by the pointers in the array.

A NULL pointer is a pointer that lacks a reference to a valid memory location. It's typically used to indicate that a pointer doesn't have a specific memory address assigned, often serving as a placeholder or default value for pointers.

Here's a code example that demonstrates the use of a NULL pointer:

In this example, we declare a pointer ptr and explicitly initialize it with the value NULL. We then use an if statement to check if the pointer is NULL. Since it is, the program will print "The pointer is NULL." This illustrates how NULL pointers are commonly used to check if a pointer has been initialized or assigned a valid memory address.

conclusion:

You've embarked on a comprehensive journey through the intricacies of C pointers. You've learned how pointers store memory addresses, enable data access, facilitate pointer arithmetic, and how they can be used with arrays and functions. Additionally, you've explored the significance of NULL pointers.

By completing this tutorial, you've equipped yourself with a robust understanding of pointers in C. You can now confidently navigate memory, manipulate data efficiently, and harness the power of pointers in your programming projects. These skills will be invaluable as you advance in your coding endeavors. Congratulations on your accomplishment, and keep coding with confidence!

Reference: C - Pointers - Tutorials Point

Pointers in C: A One-Stop Solution for Using C Pointers - simplilearn

Top comments (4)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

imperiald profile image

  • Joined Jan 7, 2024

Love your way to write articles, could you add an article for, .o files, .h files, lists and makefile? Thank you in advance!

raed_abdullah_ae4b30d82db profile image

  • Joined Aug 13, 2024

This tutorial covers the fundamentals of C pointers, providing a clear understanding of their role in memory management and data manipulation. By the end, you should be comfortable with basic pointer concepts and their applications. Are you looking to enhance your cybersecurity skills? Check out the Ethical Hacking Training in Bangalore offered by Indian Cyber Security Solutions .

cocomelonjuice profile image

  • Joined Nov 4, 2023

Great post. Thank you so much for this.

koderkareem profile image

Thank you for your kind words! I'm thrilled to hear that you enjoyed the article. Your feedback means a lot to me. If you have any questions or if there's a specific topic you'd like to see in future posts, feel free to let me know. Thanks again for your support

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

vyan profile image

🚀 Most Useful React Hooks for Your Next Project 🚀

Vishal Yadav - Aug 26

ngl4 profile image

IntelliJ IDEA: How to rename variables in multiple places in a file? ~~if you find Shift + F6 does not work...

Cindy Lam - Aug 6

bytesupreme profile image

10 Code Snippets Every Developer Should Know: Essential Tools for Everyday Coding

Byte Supreme - Aug 19

duxtech profile image

Ibuprofeno.py💊| #155: Explica este código Python

Cristian Fernando - Aug 7

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

cppreference.com

Pointer declaration.

(C11)
Miscellaneous
(C11)
(C23)

Pointer is a type of an object that refers to a function or an object of another type, possibly adding qualifiers. Pointer may also refer to nothing, which is indicated by the special null pointer value.

Syntax Explanation Pointers to objects Pointers to functions Pointers to void Null pointers Notes References See also

[ edit ] Syntax

In the declaration grammar of a pointer declaration, the type-specifier sequence designates the pointed-to type (which may be function or object type and may be incomplete), and the declarator has the form:

attr-spec-seq (optional) qualifiers (optional) declarator

where declarator may be the identifier that names the pointer being declared, including another pointer declarator (which would indicate a pointer to a pointer):

The qualifiers that appear between * and the identifier (or other nested declarator) qualify the type of the pointer that is being declared:

The attr-spec-seq (C23) is an optional list of attributes , applied to the declared pointer.

[ edit ] Explanation

Pointers are used for indirection, which is a ubiquitous programming technique; they can be used to implement pass-by-reference semantics, to access objects with dynamic storage duration , to implement "optional" types (using the null pointer value), aggregation relationship between structs, callbacks (using pointers to functions), generic interfaces (using pointers to void), and much more.

[ edit ] Pointers to objects

A pointer to object can be initialized with the result of the address-of operator applied to an expression of object type (which may be incomplete):

Pointers may appear as operands to the indirection operator (unary * ), which returns the lvalue identifying the pointed-to object:

Pointers to objects of struct and union type may also appear as the left-hand operands of the member access through pointer operator -> .

Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:

Certain addition, subtraction , compound assignment , increment, and decrement operators are defined for pointers to elements of arrays.

Comparison operators are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indices of those elements, and pointers to struct members compare in order of declaration of those members.

Many implementations also provide strict total ordering of pointers of random origin, e.g. if they are implemented as addresses within continuous ("flat") virtual address space.

[ edit ] Pointers to functions

A pointer to function can be initialized with an address of a function. Because of the function-to-pointer conversion, the address-of operator is optional:

Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other functions as arguments, etc.

A pointer to function can be used on the left-hand side of the function call operator ; this invokes the pointed-to function:

Dereferencing a function pointer yields the function designator for the pointed-to function:

Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function).

Because compatibility of function types ignores top-level qualifiers of the function parameters, pointers to functions whose parameters only differ in their top-level qualifiers are interchangeable:

[ edit ] Pointers to void

Pointer to object of any type can be implicitly converted to pointer to void (optionally const or volatile -qualified), and vice versa:

Pointers to void are used to pass objects of unknown type, which is common in generic interfaces: malloc returns void * , qsort expects a user-provided callback that accepts two const void * arguments. pthread_create expects a user-provided callback that accepts and returns void * . In all cases, it is the caller's responsibility to convert the pointer to the correct type before use.

[ edit ] Null pointers

Pointers of every type have a special value known as null pointer value of that type. A pointer whose value is null does not point to an object or a function (dereferencing a null pointer is undefined behavior), and compares equal to all pointers of the same type whose value is also null .

To initialize a pointer to null or to assign the null value to an existing pointer, a null pointer constant ( NULL , or any other integer constant with the value zero) may be used. static initialization also initializes pointers to their null values.

Null pointers can indicate the absence of an object or can be used to indicate other types of error conditions. In general, a function that receives a pointer argument almost always needs to check if the value is null and handle that case differently (for example, free does nothing when a null pointer is passed).

[ edit ] Notes

Although any pointer to object can be cast to pointer to object of a different type, dereferencing a pointer to the type different from the declared type of the object is almost always undefined behavior. See strict aliasing for details.

It is possible to indicate to a function that accesses objects through pointers that those pointers do not alias. See for details.

(since C99)

lvalue expressions of array type, when used in most contexts, undergo an implicit conversion to the pointer to the first element of the array. See array for details.

Pointers to char are often used to represent strings . To represent a valid byte string, a pointer must be pointing at a char that is an element of an array of char, and there must be a char with the value zero at some index greater or equal to the index of the element referenced by the pointer.

[ edit ] References

  • C23 standard (ISO/IEC 9899:2024):
  • 6.7.6.1 Pointer declarators (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
  • 6.7.6.1 Pointer declarators (p: 93-94)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.7.6.1 Pointer declarators (p: 130)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.7.5.1 Pointer declarators (p: 115-116)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.5.4.1 Pointer declarators

[ edit ] See also

for Pointer declaration
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 9 April 2024, at 00:10.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

12.7 — Introduction to pointers

The most useful thing we can do with an address is access the value stored at that address. The dereference operator (*) (also occasionally called the indirection operator ) returns the value at a given memory address as an lvalue:

The address-of operator (&) and dereference operator (*) work as opposites: address-of gets the address of an object, and dereference gets the object at an address.

Although this is sometimes used as an argument to not place the asterisk with the type name (instead placing it next to the variable name), it’s a better argument for avoiding defining multiple variables in the same statement.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

C++ / D2D1 / Child class: Exception thrown: read access violation. this was nullptr.

Hello, I'm trying to create a child class for my main Direct2D class to put all the generic shapes drawing functions in there to keep the main class clean

Then I create entities for both classes like so CD2DCore* D2DCore; //class for core Direct2D methods CD2DBasic* D2DBasic; //class for drawing basic Direct2D shapes

But when I'm trying to draw, say, a line through D2DBasic->DrawLine method I get an exception void CD2DBasic::DrawLine(float x1, float y1, float x2, float y2, float r, float g, float b, float a, float strokeW) { gBrush->SetColor(D2D1::ColorF(r, g, b, a)); gRT->DrawLine(D2D1::Point2F(x1, y1), D2D1::Point2F(x2, y2), gBrush, strokeW); } at the gBrush->SetColor... line stating "read access violation. this was nullptr."

However when I put this same method in CD2DCore - it draws the line without any issues. I guess it somehow doesn't inherit the parent's pointers to Direct2D stuff?

How do I resolve this?

Windows API - Win32 A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API. 2,565 questions Sign in to follow Follow

You need to understand how your code initializes those members for the CD2DCore usage case, and presumably do something similar for your derived class usage.

I get exactly the same access violation error when simply trying to access an integer variable in the parent class

in CD2DCore:

protected: int xa = 10;

in the child's method if (xa == 10) do whatever

also throws that very same nullptr exception no matter if I explicitly state xa or CD2DCore::xa or CD2DBasic::xa and when I debug in Visual Studio - I can see that under "this" value is NULL and CD2DCore memory values 'unable to read memory'

I guess there's an issue with class inheritance since I use pointers through CD2DCore* D2DCore; CD2DBasic* D2DBasic; ?

If the "this" pointer is null, you've not got a valid object. Show a short example of your code where you create an instance of the derived class and then try to reference a member.

Here's the basic code for Direct2D classes including init function and with a place where exception is thrown commented https://pastebin.com/Gef5TxyZ

then in main.cpp I declare classes globally CD2DCore* D2DCore; CD2DBasic* D2DBasic;

then in main.cpp in 'wWinMain' function I initialize Direct2D after 'hMainWnd = CreateWindowEx(...' that creates the main window and before the ShowWindow: if (!D2DCore->InitD2D(hMainWnd)) { delete D2DCore; return -1; }

then in 'WndProc' at WM_PAINT event I try drawing a line with a child class:

D2DCore->BeginDraw(); D2DCore->ClearScreen(0.0f, 0.0f, 0.0f); //x1, y1, x2, y2, r, g, b, a, thickness D2DBasic->DrawLine(0, 100, 100, 100, 0.85f, 0.4f, 0.0f, 1.0f, 2.0f); D2DCore->EndDraw(); break;

And upon accessing DrawLine child class method it causes an access violation with nullptr as marked in pastebin code

D2DCore is a pointer, where do you create the CD2DCore object that it points to?

Then I create entities for both classes like so CD2DCore* D2DCore;

This doesn't create any object, just declares a pointer that doesn't actually point to anything. Is there a place in your code that creates an instance of CD2DCore and assigns an address of that instance to D2DCore ?

Same with D2DBasic

I did create the object with ' D2DCore = new CD2DCore(); ' in wWinMain, but forgot to create D2DBasic - so I did that with 'D2DBasic = new CD2DBasic();' and now I'm getting a different access violation with nullptr at Windows' own d2d1.h at line 1295 that is:

It's caused by the first string in DrawLine method that deals with setting a color of parent's gBrush gBrush->SetColor(D2D1::ColorF(r, g, b, a));

As replied above - I did create D2DCore with 'new', just not D2DBasic... but now I also did create it with 'new' and it throws a different nullptr exception in d2d1.h when D2DBasic is trying to do gBrush->SetColor. I guess it doesn't inherit parent's pointer of gBrush?

So, what is it that's null there? If it's gBrush, then presumably your code has never set it.

It was set in the code in main.cpp like so:

InitD2D of CD2DCore generates gBrush, gRT and other stuff. But it throws an exception at that line in d2d1.h

However if I put InitD2D into the constructor of CD2DCore class - it stops crashing but will not draw anything - unless I use D2DBasic->BeginDraw / ClearScreen / EndDraw and not same functions of D2DCore. But it's not optimal since I also need stuff drawn by the D2DCore - and if I draw stuff using D2DCore I need to call its own BeginDraw etc - which causes flashing as first D2DCore is drawn and being output, then D2DBasic is drawn and being output.

I'm fairly certain gRT (render target to window) is the same for both, as I've checked it with if (CD2DCore::gRT != CD2DBasic::gRT) MessageBox( error stuff in DrawLine() of D2DBasic so why won't D2DCore->BeginDraw() work for D2DBasic?

I'm not familiar with Direct2D so I don't know what to suggest there.

As far as I see, Nobody calls InitD2D which should be called in CD2DCore constructor.

It was called right after D2DCore = new CD2DCore() and before D2DBasic = new CD2DBasic() and it was still throwing exceptions However when I put InitD2D into the constructor of CD2DCore as you suggested - the crashing stopped BUT stuff drawn through D2DBasic isn't shown through D2DCore->BeginDraw / EndDraw (which are both just methods to call render target gRT->BeginDraw / EndDraw) but is shown when I do D2DBasic->BeginDraw / EndDraw, however D2DCore graphics aren't shown through those methods - so right now I need to call those methods from both parent and child class at the same time every frame which causes flashing. This is weird since when I check if CD2DCore::gRT is equal to CD2DBasic::gRT - those pointers point to the exact same memory address so why are they treated like two separate entities?

why won't D2DCore->BeginDraw() work for D2DBasic?

According to ID2D1HwndRenderTarget interface , Your application should create render targets once and hold onto them for the life of the application or until the render target's EndDraw method returns the D2DERR_RECREATE_TARGET error. When you receive this error, you need to recreate the render target (and any resources it created).

And the code should like this:

Perhaps you should have a look at c++ Inheritance;

Interesting - will try that too. But I found another solution as well - instead of making CD2DBasic a child of CD2DCore class - I instead tried creating it as a separate class where methods accept pointers to render target and brush apart from position/color. Then I simply first create D2DBasic and call those methods from within new CD2DCore method "OnRender" where it just goes Draw, ClearScreen - then methods from D2DBasic and then EndDraw. And it works.

Edit: tried your suggestion too and it works perfectly as well. However as I'm going to have more classes dealing with Direct2D stuff like a separate class for loading and drawing bitmaps - it will be better to just use non-child way as described above, right? Since D2DCore = (CD2DCore*)D2DBasic basically ties both classes down

Yes. friend Class works perfectly as well.

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Access violation reading location

  Access violation reading location

pointer assignment access violation c

MoneyBoxHandler::MoneyBoxHandler() { ->capacity=3; ->nrOfBoxes=0; ->moneyBoxes= MoneyBox*[ ->capacity]; ( i=0;i< ->capacity;i++) ->moneyBoxes[i]=NULL; } MoneyBoxHandler::MoneyBoxHandler( size) { ->capacity=size; ->nrOfBoxes=0; ->moneyBoxes= MoneyBox*[ ->capacity]; ( i=0;i< ->capacity;i++) ->moneyBoxes[i]=NULL; } MoneyBoxHandler::~MoneyBoxHandler() { ( i=0;i< ->nrOfBoxes;i++) ->moneyBoxes[i]; [] ->moneyBoxes; ->moneyBoxes=NULL; } MoneyBoxHandler::MoneyBoxHandler( MoneyBoxHandler &obj) { ->capacity=obj.capacity; ->nrOfBoxes=obj.nrOfBoxes; ->moneyBoxes= MoneyBox*[ ->capacity]; ( i=0;i< ->capacity;i++) ->moneyBoxes[i]=NULL; ( i=0;i<obj.nrOfBoxes;i++) ->moneyBoxes[i]=obj.moneyBoxes[i]; } MoneyBoxHandler& MoneyBoxHandler:: =( MoneyBoxHandler &obj) { ->capacity=obj.capacity; ->nrOfBoxes=obj.nrOfBoxes; ->moneyBoxes= MoneyBox*[ ->capacity]; ( i=0;i< ->capacity;i++) ->moneyBoxes[i]=NULL; ( i=0;i<obj.nrOfBoxes;i++) ->moneyBoxes[i]=obj.moneyBoxes[i]; * ; } MoneyBoxHandler::addMoneyBox(string owner) { ( ->nrOfBoxes== ->capacity) { ->capacity+=2; MoneyBox **temp= MoneyBox*[ ->capacity]; ( i=0;i< ->capacity;i++) temp[i]=NULL; ( i=0;i< ->nrOfBoxes;i++) temp[i]= ->moneyBoxes[i]; [] ->moneyBoxes; ->moneyBoxes=temp; temp=NULL; } ->moneyBoxes[ ->nrOfBoxes++]= MoneyBox(owner,0); } MoneyBoxHandler::addMoneyToMoneyBox(string owner, amount) { done= ; ( i=0;i< ->nrOfBoxes&&!done;i++) { ( ->moneyBoxes[i]->getOwner()==owner) { ->moneyBoxes[i]->add(amount); done= ; } } } MoneyBoxHandler::showAll() { ( i=0;i< ->nrOfBoxes;i++) { cout<< ->moneyBoxes[i]->getOwner()<<endl; cout<< ->moneyBoxes[i]->getBalance()<<endl; } }
test1(MoneyBoxHandler &mbh) { mbh.addMoneyToMoneyBox( , 200); } test2(MoneyBoxHandler &mbh) { mbh.addMoneyToMoneyBox( , 300); mbh.addMoneyToMoneyBox( , 100); } MoneyBoxHandler test3() { MoneyBoxHandler mbh(3); mbh.addMoneyBox( ); mbh.addMoneyToMoneyBox( , 800); mbh; } print(MoneyBoxHandler &mbh) { mbh.showAll(); } main() { _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); MoneyBoxHandler mbh1(6); MoneyBoxHandler mbh2(8); mbh1.addMoneyBox( ); mbh1.addMoneyBox( ); mbh2.addMoneyBox( ); test1(mbh1); test2(mbh2); MoneyBoxHandler mbh3 = mbh1; MoneyBoxHandler mbh4; mbh4 = mbh2; print(mbh1); print(mbh2); print(mbh3); print(mbh4); mbh4 = test3(); print(mbh4); MoneyBoxHandler mbh5 = MoneyBoxHandler(mbh3); 0; }
( i=0;i<obj.nrOfBoxes;i++) ->moneyBoxes[i]=obj.moneyBoxes[i];
->moneyBoxes[i] = MoneyBox(*(obj.moneyBoxes[i]);
MyClass { var; func( var) { var = 2; ->var = 2; } };

LWN.net Logo

  • Weekly Edition
  • Events calendar
  • Unread comments
  • Write for us

Linux 6.10.7

:  Greg Kroah-Hartman <gregkh-AT-linuxfoundation.org>
:  linux-kernel-AT-vger.kernel.org, akpm-AT-linux-foundation.org, torvalds-AT-linux-foundation.org, stable-AT-vger.kernel.org
:  Linux 6.10.7
:  Thu, 29 Aug 2024 18:06:23 +0200
:  <2024082922-module-unsaved-5f2d@gregkh>
:  lwn-AT-lwn.net, jslaby-AT-suse.cz, Greg Kroah-Hartman <gregkh-AT-linuxfoundation.org>
:  

Get the Reddit app

A subreddit for all questions related to programming in any language.

[C++] Unhandled exception/Access violation reading location

SOLVED Problem was with how the Visual Studio Project was setup. It was somehow causing cin to give the error and remaking the project fixed it.

My program runs fine, but on exit I usually get the following error;

Unhandled exception at 0x77b71206 in Final Project - Image Processing.exe: 0xC0000005: Access violation reading location 0x700763ff.

From texting i've found out the last location 0x700763ff always changes, so my guess is thats where whatever it is is currently being stored.

Googling has told me that 0xC0000005 being close to 0 means it's likely a null pointer.

And I have no idea what 0x77b71206 refrences as it seems to stay the same but google hasn't told me anything.

So I think this has something to do with cleaning up, and trying to destroy something that doesn't exist?

I'm not sure how to go about fixing this. I've made sure all my pointers point somewhere and i'm pretty sure I haven't got any code that would cause this.

I've never properly used the debugger so I can't make heads or tails of what it's telling me. I usually just look for the line number and go and check it myself to fix it. But there isn't any.

(I'm using Visual studio if it matters)

Under the location it is saying; std::_DebugHeapDelete<std::Locale::facet>

and it opens up a file called "xdebug" and points to the line "free(_Ptr);"

Any idea how I can go about collecting more info to find out what exactly is causing this? I would post some code but it's too long for here and uses SDL but I have it all on github if it would help anyone help me :)

TL;DR; Access Violation on closing

Thanks for any help :D

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Access violation writing location when using pointers

I'm trying to write a program that allows a user to input data into a text file to organize class assignments. The user can display the list of assignments, enter an assignment into the file, and search for specific course work that is due. I am having a problem where I get an access violation writing location error and I'm not entirely sure how to fix it. I have looked at previous discussions that are posted but can't quite figure out where I am going wrong in my code. This is taskList.cpp. The header file taskList.h is posted after it. I'm using VS2013.

When I debug the error is posted at line 55 in the taskList.cpp file below

list = new Task[capacity];

The header file (taskList.h)

Just to be sure that everything is made clear because there are 3 header files, 4 source files, and a text file, I am include the task.h header file and task.cpp source file.

Here is task.h:

Here is the task.cpp file, not sure if this is necessary but I am adding it for clarity:

Shepherdiss's user avatar

  • 3 Can you provide a minimal example that just shows the part of the code that you don't understand, rather than just blindly pasting your entire code and expecting us to debug it for you? –  Mankarse Commented May 24, 2014 at 5:38
  • 1 You code looks like C... Consider using more C++ and safe to use classes like string , vector and iterators. Than your errors likely to disappear. If you need that for some sort of homework - make sure to shorten your sample (but still reproducing the error) before posting here. –  Alexei Levenkov Commented May 24, 2014 at 5:39
  • @AlexeiLevenkov this is inevitably another "write crippled C++" class where the students are forbidden to use standard libraries or C++ best practises. Its almost like we need a new tag... C++89 , maybe. –  Rook Commented May 24, 2014 at 10:47
  • The part I'm struggling with is understanding what I need to do to make sure that memory for name, description, and date can be read which is the error I am getting at line 55: list = new Task[capacity]; It is probably something along the lines of what @MattMcNabb said below. It says that list is NULL. First post, I realize now that having all the code there is unnecessary @Mankarse. @AlexeiLevenkov I have to use new and delete unfortunately. –  Shepherdiss Commented May 24, 2014 at 19:40

3 Answers 3

Here is the problem:

The first line creates a pointer which currently does not point anywhere. Then you tell strcpy to copy that string to where the pointer is pointing, so it writes the string to "nowhere" (in practice: a semi-random memory location). This causes your access violation.

To fix this, replace the code with:

Do the same for description and date . Note that this means you don't need a copy-constructor or copy-assignment operator or destructor; because the default ones behave correctly.

Of course you will need to change your accssor functions (but they were badly designed anyway since the caller cannot prevent a buffer overflow):

Also, change Task *list; to std::vector<Task> list; and stop using new and delete . The vector correctly manages memory for you.

It is simplest and easiest to do this task without using pointers or manual memory management or C-library functions such as strcpy . You'll halve your code size (at least) and it will be much less prone to error.

You may need #include <string> and #include <vector> .

M.M's user avatar

  • Thank you for your quick response, I should have included more information in the original post as there are certain requirements for this program assignment. Use dynamic array of Task to implement TaskList. Use dynamic character array to model the strings in Task, such as course name, task description and due date. The character array should be the exact size as needed, e.g "CS162" should use a character array of size 6 including '\0'. Use destructor to deallocate the dynamic memory for the object. This is why I am using new and delete. –  Shepherdiss Commented May 24, 2014 at 8:36

Since the erroe happens at allocation if an array ( list = new Task[capacity] ) i guess your problem is in default constructor of Task class. try playing with this constructor a liitle , i suggest allocating yor char arrays (names , descriptions and data) befor filling them.

somecode like name = new Char[14]; (and of course same for the other two)

Sachamora's user avatar

You have failed to follow the rule-of-five or the rule-of-zero.

The correct thing (rule-of-zero) would be to implement TaskList in terms of std::vector<Task> .

Seeing as your assignment demands that you use a "dynamic array", perhaps they don't want you to use std::vector . This means that you are stuck with manual memory management. This means that you need to correctly implement or remove the following functions:

If you do not explicitly supply these functions, the compiler may automatically generate them, and the compiler-generated versions will be incorrect (for the situation where you are manually managing resources within TaskList ), as they will do member-wise moves or copies, rather than copying or moving the underlying resources. When you then use these incorrect compiler-generated versions, your code will have strange behaviour.

For Task , you shouldn't be managing multiple resources at once. Use std::string , or otherwise write your own string class, and then use it to manage the string members of Task . If you do not, your code is almost guaranteed to be incorrect (due to a lack of exception safety).

Mankarse's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Which programming language/environment pioneered row-major array order?
  • Raspberry Screen Application
  • Amalgamated Product Isomorphism
  • A very interesting food chain
  • Why doesn't the world fill with time travelers?
  • Chess.com AI says I lost opportunity to win queen but I can't see how
  • Topology on a module over a topological ring
  • If inflation/cost of living is such a complex difficult problem, then why has the price of drugs been absoultly perfectly stable my whole life?
  • How long does it take to achieve buoyancy in a body of water?
  • How to remove obligation to run as administrator in Windows?
  • Using "no" at the end of a statement instead of "isn't it"?
  • Who was the "Dutch author", "Bumstone Bumstone"?
  • Is it advisable to contact faculty members at U.S. universities prior to submitting a PhD application?
  • A View over java.lang.String - improved take II
  • Is having negative voltages on a MOSFET gate a good idea?
  • My visit is for two weeks but my host bought insurance for two months is it okay
  • Optimal Bath Fan Location
  • about flag changes in 16-bit calculations on the MC6800
  • How do I make a command that makes a comma-separated list where all the items are bold?
  • Series with odd numbers
  • Correct Expression for Centripetal Force
  • Parody of Fables About Authenticity
  • How much missing data is too much (part 2)? statistical power, effective sample size
  • Is there a faster way of expanding multiple polynomials with power?

pointer assignment access violation c

IMAGES

  1. c++

    pointer assignment access violation c

  2. Pointer Expressions in C with Examples

    pointer assignment access violation c

  3. c++

    pointer assignment access violation c

  4. [Solved] C++ Access violation writing location 0x0...

    pointer assignment access violation c

  5. [Solved] Catching c++ "Access Violation Writing

    pointer assignment access violation c

  6. Pointers in C: A One-Stop Solution for Using C Pointers

    pointer assignment access violation c

VIDEO

  1. Assignment Operator in C Programming

  2. Programming in C| KTU S2

  3. C Language || Pointers in C || Part-4: Pointer Assignment in C || Telugu Scit Tutorial

  4. GCU PSA

  5. Learn to Code C++ Pointers: Pointer Assignment PartI

  6. Pointers in c language

COMMENTS

  1. Access Violation With Pointers?

    An access violation usually means a bad pointer. In this case, the most likely cause is running out of string before you find your delimiter. Share. Improve this answer. Follow answered Feb 8, 2010 at 3:21. Anon. Anon. 59.7k 8 8 gold badges 83 83 silver badges 86 86 bronze badges. 2.

  2. Top 20 C pointer mistakes and how to fix them

    Mistake # 15 : Off by one errors when operating on C pointers. Given a block of memory of SIZE objects pointed to by p, the last object in the block can be retrieved by using another pointer q and setting it to (p+SIZE-1) instead of (p+SIZE). Consider the code below: Plain text. Copy to clipboard.

  3. Why do I get an access violation when assigning a file pointer ...

    Always enable every warning possible—this is a really common operator precedence vs. stupid visual ambiguity thing. When you do want to do this (sparingly) I suggest marking it like !!(a = b) as an explicit override when converting assignment to bool (also forces to one-or-zero, handy—omitting the explicit comparison w/ NULL is safer here), which disables any compiler/IDE warnings as a ...

  4. C Pointers

    C Pointers. Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C.

  5. Read access violation with pointers, I feel like I shouldn't be

    You're only passing a pointer. If anything make it a 2nd parameter, and make it the size. Never exceed the allocated amount of any array ever - C will let you read and write to array[3000] of something that was declared as array[4]. This can lead to exploitable code, Remote Code Execution or a Memory Leak, depending on the type of access.

  6. How C-Pointers Works: A Step-by-Step Beginner's Tutorial

    Accessing Data through Pointers. Dereferencing Pointers: To access the data that a pointer is pointing to, you need to dereference the pointer. Dereferencing a pointer means accessing the value stored at the memory address that the pointer points to. In C, you can think of pointers as variables that store memory addresses rather than actual values.

  7. Read access violation

    TEMP=*oByte; Not related to any access violation, if your code does. exactly what you have described above then it serves no. useful purpose. You say that "oByte is the pointer which its value is the. address of TEMP." You then dereference that pointer and. assign the value to TEMP. It should be obvious that what.

  8. Access Violation

    Access Violation - Pointers in C . Access Violation - Pointers in C. Shervan360. Hello, The second printf doesn't work. could you please explain? ... At the very least, you should have got a warning from your assignment. The "array becomes a pointer" rule only applies to the left-most dimension of an array, not all of them. So [N] gets you to ...

  9. std::unique_ptr

    std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope.. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.; the managing unique_ptr object is assigned another pointer via operator= or reset().

  10. c++

    Unhandled exception at 0x00d110d9 in inteviews.exe: 0xC0000005: Access violation writing location 0x00d27830. I really don't see what the problem is. current cell gets the value of the next cell.

  11. Pointer declaration

    Pointers to functions. A pointer to function can be initialized with an address of a function. Because of the function-to-pointer conversion, the address-of operator is optional: void f (int);void(* pf1 )(int)=& f;void(* pf2 )(int)= f;// same as &f. Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied ...

  12. [C++] Access violation on assignment operator overload

    I'm trying to overload the assignment operator for copy control on a class called directory, which contains an array of pointers to Entry class objects. I have to dereference these in order to change the value as opposed to simply making the pointers the same, but I can't dereference a null value, but I need to delete the array to make room for ...

  13. Access violation

    First-chance exception at 0x00c86e38 in Assignment 3.exe: 0xC0000005: Access violation writing location 0x00000088. ... Access violation on a memory address like 0x00000088 that is almost 0 suggest that you are trying to access an object through a null pointer. ... Inside of readfile you're trying to access the BTNode pointer passed in but it's ...

  14. 12.7

    The size of the pointer is always the same. This is because a pointer is just a memory address, and the number of bits needed to access a memory address is constant. Dangling pointers. Much like a dangling reference, a dangling pointer is a pointer that is holding the address of an object that is no longer valid (e.g. because it has been ...

  15. C++ / D2D1 / Child class: Exception thrown: read access violation. this

    And upon accessing DrawLine child class method it causes an access violation with nullptr as marked in pastebin code. 0 votes Report a concern. David Lowndes 4,711 ... This is weird since when I check if CD2DCore::gRT is equal to CD2DBasic::gRT - those pointers point to the exact same memory address so why are they treated like two separate ...

  16. Access Violation error in Pointers in C

    When you call month_day() you are passing pointers to ints which have no ints associated with them. int day; int month; int * pday = &day; int * pmonth = &month; or more simply

  17. Pointers

    Pointers can be used to access a variable by its address, and this access may include modifying the value pointed. But it is also possible to declare pointers that can access the pointed value to read it, but not to modify it. For this, it is enough with qualifying the type pointed to by the pointer as const. For example:

  18. c++

    char *strOu = ""; is a pointer to an empty string (char array of length 1). When, in the function, you write strOut += 17;, that advances the pointer by 17 characters. Now the pointer is pointing into the wilderness . It's likely that this is in a read-only data area which is why the call to strcpy_s causes an access violation.. To fix this you need to only write to memory that has been ...

  19. Access violation reading location

    Mar 10, 2011 at 6:15am. Spot (4) Hi everyone! My code builds fine but I'm getting the error: Unhandled exception at 0x00413b62 in Tenta_1_del_3.exe: 0xC0000005: Access violation reading location 0xfeeefeee when I'm running it in debug-mode. My constructors, destructors, copyconstructor and overloaded assignment operator should be correct so I ...

  20. Linux 6.10.7 [LWN.net]

    From:: Greg Kroah-Hartman <gregkh-AT-linuxfoundation.org> To:: linux-kernel-AT-vger.kernel.org, akpm-AT-linux-foundation.org, torvalds-AT-linux-foundation.org, stable ...

  21. [C++] Unhandled exception/Access violation reading location

    My program runs fine, but on exit I usually get the following error; Unhandled exception at 0x77b71206 in Final Project - Image Processing.exe: 0xC0000005: Access violation reading location 0x700763ff. From texting i've found out the last location 0x700763ff always changes, so my guess is thats where whatever it is is currently being stored.

  22. c++

    Of course you will need to change your accssor functions (but they were badly designed anyway since the caller cannot prevent a buffer overflow): std::string getName() const { return name; } Also, change Task *list; to std::vector<Task> list; and stop using new and delete. The vector correctly manages memory for you.