简体   繁体   中英

Why my code doesn't work when i change line of pointer=&number;?

I used the malloc function in this example. Problem is when I remove the line of pointer=&number;or move to different line I can't receive number entered from keyboard. I am trying to receive numbers entered by keyboard.

#include "stdio.h"
#include "stdlib.h"

int main(){
    int *pointer,number;
    printf("Please write a number: ");
    scanf("%d",&number);
    pointer=(int *)malloc(number*(sizeof(int)));
    if(pointer!=NULL){
        pointer=&number;  /*When i try to move this line to below or to up i can't receive number in address of pointer.*/
        printf("Number entered: %d\n",*pointer);
    }else{
        printf("Memory is not divided.");
        return 0;
    }
    free(pointer);
    return 0;
} 
pointer = &number;

should be

*pointer = number;

You're replace the pointer that you got with malloc() , with a pointer to the local variable, which causes a memory leak. And then when you later call free(pointer); , you're trying to free a pointer to a local variable, not the memory that was allocated, which causes undefined behavior.

And if you're only storing 1 number into the allocated memory, there's no need to multiply when calling malloc() . It should just be

pointer = malloc(sizeof(int));

Full tested script:

#include "stdio.h"
#include "stdlib.h"

int main(){
    int *pointer,number;
    printf("Please write a number: ");
    scanf("%d",&number);
    pointer=malloc(sizeof(int));
    if(pointer!=NULL){
        *pointer=number;
        printf("Number entered: %d\n",*pointer);
    }else{
        printf("Memory is not divided.");
        return 0;
    }
    free(pointer);
    return 0;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM