-2

I am writing a C ++ program that needs to convert numbers from decimal to binary. Here is my code:

int* convertToBinary(int i, unsigned int n) {
    int ans[10000];
    if (n / 2 != 0) {
        convertToBinary(i + 1, n / 2);
    }
    ans[i] = n / 2;
    return ans;
}

void send_number(int num) {
    
    for (int j = 0; j < 16; j++) {
        printf("%d", convertToBinary(0, num)[j]);
    }   
}

In this case, the num variable takes only natural values from 0 to 65535.

The main function is send_number().

On execution I get the 'Segmentation fault (core dumped)' error. I can't figure out why this is happening.

PS: I am C++ beginner. I don't know English well and use google translator

  • Have you checked that i < 10000 before doing ans[i] = n / 2; – Omid CompSCI Sep 11 '21 at 20:51
  • 4
    Does this answer your question? [What is a dangling pointer?](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer) and [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Richard Critten Sep 11 '21 at 20:51
  • 1
    DId you try to debug the code? To see what is causing the error. – Quimby Sep 11 '21 at 20:51
  • Quimby, no, i didn't. Thank you for your advice! – Matvey Polubryukhov Sep 11 '21 at 20:57
  • Also, consider you are allocating 100,000 elements on the stack, recursively. You will run out of stack space. – ChrisMM Sep 11 '21 at 21:00

1 Answers1

0

There are 2 issues at play - scope and (related) dangling pointers. When you define any variable inside a function - it is only valid inside that function.

convertToBinary returns a pointer that refers to invalid memory. So when you try to print it - you are using convertToBinary(0, num)[j]

Think about what this does. You take an invalid pointer returned by the function and add an offset j to it.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
moi
  • 467
  • 4
  • 19
  • I think I understand you. But I still have a couple of questions. Can I return from a function not a pointer to memory, but the value itself? Or maybe it is possible to return a pointer that is valid outside of the function? – Matvey Polubryukhov Sep 11 '21 at 21:07
  • @MatveyPolubryukhov You can do either of those things. You can even return a pointer to an object that no longer exists, like your code does, so long as you don't dereference that pointer. – David Schwartz Sep 11 '21 at 21:40
  • @MatveyPolubryukhov - there are different types of memory here - stack is allocated within the function and heap is allocated using new/delete and malloc/free. – moi Sep 12 '21 at 08:43
  • To simplify things, until you understand memory allocation, do not return a pointer from a function just return a value. – moi Sep 12 '21 at 08:44