Juraj
Juraj

Reputation: 63

Rewrite values from one pointer to another

I would like to rewrite values from one pointer to another. I have got two matrixes that used in code and everything well. They are allocated, have the same sizes, and are created in structs.

typedef struct{
  int rows;
  int cols;
  int *values;
} matrix;

Here is the code how I rewrite them:

m1->values = m2->values;

This way rewrites them properly, but Valgrind shows:

Invalid free() / delete / delete[] / realloc()

Deallocation works until I want to rewrite it. How can I rewrite values without this problem? Is it possible? Heap summary says: total heap usage: 8 allocs, 8 frees, 5,240 bytes allocated

Upvotes: 0

Views: 123

Answers (1)

meaning-matters
meaning-matters

Reputation: 22986

Your values is declared as a pointer to int. (This means that values contains just the address of memory that you must allocate somewhere.)

This means that m1->values = m2->values; only copies the memory address that's stored in values.

In order to copy, you need something like:

#include <string.h>

size_t size = m2->rows * m2->cols * sizeof(int);
m1->values = malloc(size);
memcpy(m1->values, m2->values, size);

I assuming you understand that you also need to allocate memory for m2->values to begin with.

Upvotes: 1

Related Questions