The moment you do bb = first;, bb and first are pointing to the same location of memory. first->a = 55; first->b = 55; first->c = 89; will change the values for a, b, and c in that location. The original value of first, is still lingering in memory but no way to access it anymore.

I think what you may want to do is *bb = *first;.

Answer from Anzurio on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp_questions โ€บ does assigning a pointer to another pointer create a copy or does it just point to the same variable like a reference? if so whats the difference between using a pointer and a reference?
r/cpp_questions on Reddit: Does assigning a pointer to another pointer create a copy or does it just point to the same variable like a reference? If so whats the difference between using a pointer and a reference?
May 9, 2022 - Also read chapter 9 at https://www.learncpp.com/ (and all the other chapters too). ... A raw pointer behaves just like an int, as it has no other behaviour. So copying one has exactly the same behaviour as copying an int, except you are copying addresses not numbers (ok, an address is a number at the end of the day, but you are not allowed to treat it as a number).
Discussions

Copy pointer to pointer in function - C - C++ Forum
Hello, I'd like to copy pointer to pointer in function and I don't want to use the library. But in main I have the old string instead a new string. Thanks ... Line 10 is just overwriting Str1, which is a local variable. If you need to change a pointer in main, you need two levels of indirection ... More on cplusplus.com
๐ŸŒ cplusplus.com
January 28, 2021
c - When should I copy a pointer inside a function? - Software Engineering Stack Exchange
Stack Exchange network consists ... their careers. Visit Stack Exchange ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm trying to teach myself programming and I'd really appreciate some help with this issue. I've just read a tutorial on pointers but I have a problem with the example. The function copies one string ... More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
c - Copying data in pointers - Stack Overflow
What if I just want to point to the GPSLocation when creating another thread after doing the copy mentioned above? ... For just pointing to same memory use GPSLocation *destination = (GPSLocation *) ptr;. But be careful, because if you modify this memory via the pointer, the original one will ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 20, 2011
c - How to copy data to a pointer returned by malloc? - Stack Overflow
In order to understand the memory ... does in C. In the words of the standard: In simple assignment (=), the value of the right operand [...] replaces the value stored in the object designated by the left operand. In simple down-to-earth words, the left operand forgets the value it was holding before, and starts holding something else. Now let's recall that a pointer is a value that points to some data (an object, or a block of memory). What are these values that are copied and forgotten ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 9846
Copying pointers. - C++ Forum
Warnis is right, pointers store values just like any other variable, but they store a special value, the adress of an object.But you can still work with their value just like any other variable. ... when you say array2[1] = array1[1];, it means 'the second pointer variable in array2 should point to the address stored in the second pointer variable of array1. (remember arrays start at 0). If you want to copy array1 completely to array2, you'll need to copy each element one by one, of course using a loop structure.
๐ŸŒ
HowStuffWorks
computer.howstuffworks.com โ€บ tech โ€บ computer software โ€บ programming
Pointers: Pointing to the Same Address - The Basics of C Programming | HowStuffWorks
March 8, 2023 - Note that in this code, r points to the same thing that p points to, which is i. You can assign pointers to one another, and the address is copied from the right-hand side to the left-hand side during the assignment.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-copy-a-pointer-to-another-pointer-in-the-programming-language-C
How to copy a pointer to another pointer in the programming language C++ - Quora
Answer: There are two ways thus can be done: 1. Do a shallow copy by assigning pointer A to pointer B 2. Do a deep copy by creating a new object by doing a deep copy of pointer Aโ€™s object into a new object K. The address of the newly created ...
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 275738
Copy pointer to pointer in function - C - C++ Forum
January 28, 2021 - Hello, I'd like to copy pointer to pointer in function and I don't want to use the library. But in main I have the old string instead a new string. Thanks ... Line 10 is just overwriting Str1, which is a local variable. If you need to change a pointer in main, you need two levels of indirection ...
Find elsewhere
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 124584-copying-structures-containing-pointers.html
Copying structures containing pointers
March 10, 2010 - obj2=obj1; (*obj2.x1)++; printf("obj2 ... only normally. But if you want to new memory you need to allocate the new memory. ... I guess that if I use the memcpy function, I will get a copy of the structure pointer only and not the whole allocated area via this pointer...
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ c-copying-data-using-the-memcpy-function-in-c
C: Copying data using the memcpy() function in C
In C, the memcpy() function copies n number of characters from one block of memory to another. ... Destination: Pointer to the destination array where data will be copied.
๐ŸŒ
Bytes
bytes.com โ€บ home โ€บ forum โ€บ topic
Get copy of object from pointer? - C / C++
November 1, 2015 - In other words, ask p to copy itself, rather than perform a copy-by-value operation by dereferencing the pointer and that assumes that p is a pointer to an exact type. Greg ... Re: Get copy of object from pointer? Mike wrote:[color=blue] > I have a class "Call".
๐ŸŒ
W3Schools
w3schools.in โ€บ c-programming โ€บ examples โ€บ copy-string-using-pointers
C Program to Copy String Using Pointers - W3Schools
The printf() function again used to display the target string copied from the source string. Now, after the main() ends, the user-defined function is declared and defined where its return type is void, then the name of the function - copy_string() which passes two character type pointer values ...
Top answer
1 of 1
5

Is there something wrong with it?

Yes, there is. In each of these cases there is a memory leak. In addition, some of these snippets may do the wrong thing (i.e. the program gives a wrong answer in addition to leaking memory, or just crashes).

In order to understand the memory leak, let's review what assignment does in C. In the words of the standard:

In simple assignment (=), the value of the right operand [...] replaces the value stored in the object designated by the left operand.

In simple down-to-earth words, the left operand forgets the value it was holding before, and starts holding something else.

Now let's recall that a pointer is a value that points to some data (an object, or a block of memory).

What are these values that are copied and forgotten in these statements?

p = malloc(sizeof(something));

// p stores the value returned by malloc, which is a pointer to 
// a block of memory. note that this value is the only pointer in 
// existence that points to that block of memory.

p = something_else;

// p forgets that it was storing a pointer to a block of memory 
// returned by malloc, and now stores a different pointer,
// presumably pointing to another block of memory. 
// the old pointer is now lost forever. there is no other pointer
// that points to the same block.

This is the very definition of memory leak.

Note that the block of memory itself is not touched or modified in any way, shape, or form. Only pointers are changed.

It's the confusion between the pointer and the pointed-to data that leads to this error. It seems that people commit it operate under a false impression that p = malloc(...) allocates space for data, and p = something_else assigns the data to space just allocated. This is indeed not how pointers work. Both statements only assign pointers, and do not touch pointed-to data.

What would be the right way to do this?

It depends on what is "this", i.e. on what you need. There is no universal recipe. In some cases you just want to copy a pointer. Drop the malloc line, and use the second assignment directly:

p = something_else; // no malloc here, just pointer assignment

In other cases you need to copy data pointed to by something_else into a new block of memory returned by malloc and now pointed by p (as opposed to something_else itself, which is a pointer):

p = malloc(sizeof(*p));           // note how sizeof is used here.
copy_data (p, something_else);    // always prefer this over sizeof(some_type)

Of course there is no such thing as copy_data in C. This is something you need to provide yourself, or use one of the standard functions. For example, if you need to copy a string:

p = malloc(strlen(something_else) + 1); // note no sizeof here. the size is dynamic
strcpy(p, something_else);              // also note +1 for the null terminator

// these two lines can be replaced by p = strdup(something_else);
// strdup is a function that has recently entered the C standard, but it was
// supported by all major compilers since the dawn of time

If you need to shallow-copy a struct:

p = malloc(sizeof(*p));
memcpy(p, something_else, sizeof(*p));
// or, if both p and something_else are declared 
// as pointers to struct something
*p = *something_else;

// if the struct contains pointers, this is probably not what you want
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 2545188 โ€บ how-can-i-do-a-copy-of-a-pointers-list-c
How can I do a copy of a pointers list? C++
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-write-a-C-program-that-uses-pointers-to-copy-an-array-of-integers
How to write a C program that uses pointers to copy an array of integers - Quora
Answer (1 of 4): Iโ€™m not going to give you the answer, but I will explain some concepts. You may be confused by how C does array access. You cannot copy an array by trying to do an assignment. Say you have two integer arrays, a and b. You cannot copy a into b by doing: [code]b = a; [/code]In fa...
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 77799 โ€บ copying-data-from-one-pointer-to-another
c++ - copying data from one pointer to another [SOLVED] | DaniWeb
May 9, 2007 - Note that strdup is convenient but POSIX, not ISO C/C++; if you use it, include proper cleanup and know its portability limits (strdup on POSIX). For general structs: if a struct only contains plain values (no pointers), assignment or memcpy performs a full copy. If it contains pointers, you must perform a deep copy for each pointed-to resource:
Top answer
1 of 7
21

To copy strings in C, you can use strcpy. Here is an example:

#include <stdio.h>
#include <string.h>

const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);

If you want to avoid accidental buffer overflows, use strncpy instead of strcpy. For example:

const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
2 of 7
17

To perform such manual copy:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* orig_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char* ptr = orig_str;

    // Memory layout for orig_str:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // |A|B|C|D|E|F|G|H|I|J|K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z |\0|  --> data
    // ------------------------------------------------------------------------

    int orig_str_size = 0;
    char* bkup_copy = NULL;

    // Count the number of characters in the original string
    while (*ptr++ != '\0')
        orig_str_size++;        

    printf("Size of the original string: %d\n", orig_str_size);

    /* Dynamically allocate space for the backup copy */ 

    // Why orig_str_size plus 1? We add +1 to account for the mandatory 
    // '\0' at the end of the string.
    bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));

    // Place the '\0' character at the end of the backup string.
    bkup_copy[orig_str_size] = '\0'; 

    // Current memory layout for bkup_copy:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // | | | | | | | | | | |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |\0|  --> data
    // ------------------------------------------------------------------------

    /* Finally, copy the characters from one string to the other */ 

    // Remember to reset the helper pointer so it points to the beginning 
    // of the original string!
    ptr = &orig_str[0]; 
    int idx = 0;
    while (*ptr != '\0')
        bkup_copy[idx++] = *ptr++;

    printf("Original String: %s\n", orig_str);   
    printf("Backup String: %s\n", bkup_copy);

    return 0;
}
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ different-ways-to-copy-a-string-in-c-c
Different ways to copy a string in C/C++ - GeeksforGeeks
July 23, 2025 - We can use the inbuilt function strcpy() from <string.h> header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination ...
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ c-how-to-properly-copy-the-value-of-a-pointer
Correct Way to Duplicate Pointer Value in C++
April 8, 2023 - If testObj is not a pointer typedef, ... new. Additionally, it is important to assign an address to pointer p before utilizing *p . When copying pointers, p2 = p1; is the correct approach as the copy will reference the same object as the original....