Here is the code:

int *p; // так как в функцию указатель в таком виде передать нельзя: компилятор заругается, то: p = (int*)malloc(sizeof(int)); // в функции я переопределю его размер через realloc func(p); for (i = 0; i < count; i++) printf("%d ", p[i]); // возвращает мусор /* если из функции делать вывод, то в консоль выводятся корректные значения */ 

Help me understand what's the matter?

func function prototype:

 void func(int *arr); 

I don’t want to do int * yet: I want to understand what’s wrong here ...

  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin

2 answers 2

So, you have a pointer int* p; and you want to initialize it through a function call. You can do this:

  void func(int** inPtr){ int* tmp = (int*)malloc(0x100); *inPtr = tmp; //(*inPtr)[2] = 0x02;//пишем 3-й элемент } void main(void){ int* p; func(&p); //printf("0x%X\n", p[2]);//читаем 3-й элемент } 

func takes a pointer to a pointer to an int, that is, the address of a pointer to an int. In main, we received the address of our pointer through a link and passed it to the function. In the function, we got the pointer itself through dereference from the address and wrote down the allocated buffer into it.

Dances with tmp are needed so that in the debugger you can see the real address of the allocated buffer and compare it with what will be in p after executing fun ()

  • Thank you very much for the explanation, but the question arose: Is it not correct to write int *p; etc. everywhere, emphasizing that this is a pointer and not a data type? - Setplus
  • @Setplus I do not know. I'm seeing int * foo; I understand that this is a variable with the name foo, and its type is an "int pointer", that is, a pointer to an integer. I got used to it, explained to myself, it works as it should. - Vladimir Martyanov
  • and how then to interpret int** ... ? - Setplus
  • @Setplus (int pointer) pointer, that is, a pointer to a pointer to an integer, as I wrote :-) - Vladimir Martyanov
  • 2
    @Setplus need not be embarrassed and be bold and cheerful - Igor

I didn’t quite understand why it’s impossible to pass a pointer to a function and what kind of garbage it turns out, so I’ll just try to answer with an example:

 #include <stdio.h> #include <stdlib.h> #define COUNT 15 void func(int *arg) { if((arg = (int*)malloc(sizeof(int) * COUNT)) == NULL) printf("allocation error\n"); } int main() { int *p, i; // почему в таком виде нельзя передать? func(p); // если в func() произошел allocation error, будет ошибка, // т.к. мы ничего не узнаем об этом // меняем мусор на что-то осмысленное for (i = 0; i < COUNT; i++) *(p + i) = i; // выводим массив for (i = 0; i < COUNT; i++) printf("%d ", p[i]); printf("\n"); return 0; } 
  • one
    memory leak in func, in cycles in main dereferencing of uninitialized pointer - mymedia
  • @mymedia in more detail please? How can segfault be achieved with such crutches? I would be grateful if you explain. - n3r0bi0m4n
  • @mymedia i.imgur.com/JfUMgYj.png or have you changed something? I did not notice, maybe. - n3r0bi0m4n
  • 2
    Nah, I haven't changed anything. This is just an undefined behavior - in one case it works, in the other - no. You need to fix it so that the address of the pointer is passed to func, and not the value of the pointer itself. See an example in the answer of Vladimir Martyanov. - mymedia