0

I have a function which gets as a parameter a pointer to array, e.g. int** segs. I need to allocate (in the function-body) memory for the array, which has size 100 for example. My attempt was:

*segs=(int*)(malloc(100));

So far so good. I put a value into *segs[0], and still everything is great. But... when I try to reach *segs[1], I get an "invalid write of size 4" error from valgrind, which leads to seg-fault. I have no idea why does that happen. I tried to reach to *segs[2], but then I get even something weirder-

Error of uninitialised value of size 8.

4
  • 1
    Please try to create an minimal reproducible example to show us of your attempt. Commented Dec 10, 2018 at 20:22
  • Did you really mean C++? Because this sounds like C code. There is zero reason to write code like this in C++. Commented Dec 10, 2018 at 20:23
  • 1
    I put a value into *segs[0] - be care of operator precedence. Either disambiguate, e.g (*segs)[0] = ... or use a local var and save to your target ptr-to-ptr after everything else is done. Commented Dec 10, 2018 at 20:23
  • Is there anything at *segs? Commented Dec 10, 2018 at 20:26

1 Answer 1

4

Due to operator precedence, *segs[N] is treated as *(segs[N]), which is ok when N is equal to 0. However, when you do the same thing using the index 1, things break since nothing has been allocated for segs[1]

For any index other than zero, you need to use (*segs)[N].

It will be easier to use a temporary pointer in the function.

int* ptr = (int*)(malloc(100));
*segs = ptr;

// and then

ptr[0] = ...;  // Good
ptr[1] = ...;  // Good

...


ptr[99] = ...; // Still good

Upgrading to C++ Way

  1. Pass the pointer by reference.

    void foo(int*& segs) { ... }
    
  2. Use new instead of malloc to allocate memory.

    segs = new int[100];
    
  3. Better yet, use std::vector insteady raw arrays.

    void foo(std::vector<int>& segs) { ... }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.