Why do I get "Segmentation Fault", but if I remove * in the printf call it doesn’t happen?

Asked

Viewed 38 times

0

int alloc(int * pointer, int num){
    scanf("%d", &num);
    pointer = (int *) malloc(num*sizeof(int));
    return(*pointer);
}

int main(){
    int *pointer;
    int num;
    alloc(pointer, num);
    printf("%d", *pointer);
    return 0;
}
  • Please Speak English.

  • When you are doing alloc, it gives Return on *Inter, so I think the printf doesn’t need the *

  • What did you try to do with this code? In function alloc you pass a parameter num that is read from the user and is only used to set the size of memory allocated in pointer. In the printf you try to display the value on the pointer, which has been allocated but with no value assigned. What would be the expected result?

  • @Ianmoone The return of the function in this case is indifferent given that in the call of alloc the return is ignored.

  • @Andersoncarloswoss was actually just an activity I’ll pass you the question: Implement a function that dynamically allocates a vector of integers. This function should take as parameter an integer representing the size of the vector, and return a pointer representing the allocated vector. I guess I got the question wrong by the way, and I wanted to print the pointer address only

  • @Maurydeveloper I thought the forum was only in English, sorry

  • Note that the way you built your alloc function you will be placing the address of the memory area allocated with malloc in the function parameter stack and not in the variable defined in your main.

  • For more details see the very didactic and explanatory answer of Jefferson Quesado on: https://answall.com/questions/403341/ponteiro-vindo-de-uma-fun%C3%A7%C3%a3o-n%C3%a3o-imprime

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.