简体   繁体   中英

What does a cast from malloc return?

I am trying to understand what is returned on the last line to name p.

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a;
    int* p;
    p = (int*)malloc(sizeof(int));
}

Q1
Assuming malloc(sizeof(int)) returns &name (name can be x or y or w), is it safe to interpret the line as p=(int*)(memoryAddress to begining of block size) ?

Q2
Can somebody rewrite this to make it more clear? Maybe add a line before p=.. I am a beginner at C++.

This is a link to an image of how I am trying to understand everything... this is just for reference
图片

    p = (int*)malloc(sizeof(int));

This line is simply allocate 4 byte (the actual size is depends on the compiler though) of memory and return the address of first byte. That first byte address is assigned to p.

The return type of malloc is generic (void *). So we need to cast it to int * to use this as integer. By saying "use it as integer", it means that 4 bytes of consecutive memory will be used as one data.

So, if you put a data in that variable as follows:

*p=1234

It will use all 32 bit memory starting from the memory location stored in p.

Regarding safety, read the comment.

I think I have figured it out.

Malloc just allocated memory of sizeof(type) Then it only returns a (void ) and in c++ an int* p cannot be assigned a void* because c++ is strict about "implicit casting".*

So the answers

Q1 Answer
Assumption is wrong, malloc(sizeof(int)) returns type void* of first byte of number of bytes allocated for sizeof(...)

Q2 Answer
this can be rewritten as

#include <stdio.h>
#include <stdlib.h>
int main(){
int* p;
p = new int;
}


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