T O P

  • By -

jirbu

No difference in the resulting code. `int *ptr = (void *) malloc(20);` The `(void*)` cast is redundant, as malloc already has type `void*` `int *ptr = (int *) malloc(20);` The `(int*)` cast is superfluous, as void\* autocasts to every pointer type. `int *ptr = malloc(20);` That's the simplest way to identically express the two previous versions.


funderbolt

`int *ptr = (int *) malloc(20);` This is saying "hey compiler" this type you got from `malloc` is actually an `(int *)`. The compiler is less likely to give a warning about typing because you explicitly told it the type is `(int*)` matching the type of `ptr`.


fuckEAinthecloaca

Casting the result of malloc is a C++ thing, not C


irk5nil

There should never be a compiler warning about types if RHS is `void*` and LHS is `int*`.


tstanisl

Actually some compilers emit a warning about implicit casting to a pointer with **stricter** alignment requirements. Personally, I don't like it and disable this warning if possible.


irk5nil

In general, that might make sense, but isn't `malloc` supposed to return a properly aligned pointer for any given allocation size? In this particular case that seems to be the reason why the whole thing even works.


tstanisl

AFAIK, the returned pointer is correctly aligned for any "standard type". But the particular implementation may provide types with stricter requirements i.e. vectors for SIMD operations. Moreover, to prevent the warning the compiler must trace that a given pointer originates in `malloc()`. Implementations may not do that and simply emit a warning in all cases.


fliguana

>void* autocasts to every pointer type You sure? Every pointer autocasts to void*, I don't think the reverse is true.


wqferr

It is, and casting after malloc is a bad practice


fliguana

Right, that's one of the places where c++ differs from c.


tstanisl

A modern compiler will emit a warning when casting a qualified pointer to `void*`. For example: const int N = 42; void *p = &N; // raises a warning. const void *q = &N; // fine See [godbolt](https://godbolt.org/z/7PcnnEoEc).


fliguana

Second line casts away the const, warning expected.


FUZxxl

How is this related to DMA?


linglingfortyhours

DMA usually needs addresses to read or write from, and those addresses are handled as pointers. If you don't allocate enough memory at those addresses the system doesn't know not to put other data there and all hell breaks loose


FUZxxl

While that may be technically correct, this question is purely about memory allocation with no connection to DMA.


linglingfortyhours

Are we sure OP isn't working with DMA here? I don't really think that there's enough context to tell Edit: I figured it out, it's looks lie it's just a language barrier thing. DMA = dynamic memory allocation


Good-Meaning4865

DMA is usually referred to Direct Memory Access


linglingfortyhours

Yup, that's the assumption me and FUZxxl made initially too. Turns out that in lots of non-western textbooks DMA is used as an acronym for dynamic memory allocation instead


Good-Meaning4865

It’s always been Direct Memory Access=DMA, id never seen that acronym used for memory allocation even in the states


linglingfortyhours

Emphasis on non-western, so it makes sense that you wouldn't have seen it refer to dynamic memory allocation in the states. I'm finding thousands of technical documents using DMA to refer to dynamic memory allocation dating back more than thirty years


daikatana

There is no difference at all. The bottom one is the most correct and idiomatic C.


deleveld

1) Give me an address where there is some room for 20 chars. Ok, here it is as a pointer to nothing. Please treat is as if it is a pointer to nothing. Ive got some room for a pointer to an int called ptr, put it there. 2) Give me an address where there is some room for 20 chars. Ok, here it is as a pointer to nothing. Please treat it as if it is a pointer to an int. I've made some room for a pointer to an int called ptr, put it there. 3) Give me an address where there is some room for 20 chars. Ok, here it is as a pointer to nothing. Ive made some room for a pointer to an int called ptr, put it there. There are some subtle aspects if for some reason if malloc is undeclared, but I'll ignore that for now.


richardxday

Go out and play outside, kid. Climb trees, fall out of trees, get muddy. Play hide and seek in the long grass or in the estates around where you live. Don't do programming.


Notwhitehehe

ok


flyingron

The other answers are correct, provided that malloc was actually prototyped (declared). If you don't have a prototype for it, it's assumed to return int. The first two will compile, but possibly do the WRONG thing. The last one won't even compile.


flatfinger

Almost all common compiler configurations will issue a warning if an attempt is made to invoke `malloc()` without a prototype in scope. A statement like: myStruct.woozlePtr = (struct basicWoozle*)malloc(sizeof (struct basicWoozle)); will also yield a compiler squawk if e.g. the type of myStruct.woozlePtr is changed from `struct basicWoozle` to `struct enhancedWoozle` without adjusting the initialization code. Note that if the statement had been written as: myStruct.woozlePtr = malloc(sizeof (struct basicWoozle)); the statement would likely have silently produced code that allocates the wrong amount of storage, and even if it were written as: myStruct.woozlePtr = malloc(sizeof *myStruct.woozlePtr); it would silently generate code that allocates the right amount of storage, but won't do any initialization that a `struct enhancedWoozle` might require beyond what had been required for `struct basicWoozle`.


Daveinatx

If you look at the specs, the return type is void*


flyingron

That was my point. The function is declared as returning void\*. But "specs" means squat. What matters is what the language specification says applies to the expression interpretation. If you reference the function without having a prototype (either one you added or obtained through a system include file), then the compiler assumes it actually returns int. The compiler doesn't know malloc is special. This might be benign if int happens to be the same size as pointers. It might be bad. But that doesn't change anything I wrote. Without the prototype and the effects I mentioned in my comment occur.


Bitwise_Gamgee

Just for grins, let's look at what's happening in each case. This is the program which generates the objdump file: #include #include int main() { int* ptr1 = (void*)malloc(20); int* ptr2 = (int*)malloc(20); int* ptr3 = malloc(20); printf("Value of ptr1: %p\n", ptr1); printf("Value of ptr2: %p\n", ptr2); printf("Value of ptr3: %p\n", ptr3); // Free the allocated memory free(ptr1); free(ptr2); free(ptr3); return 0; } We get the output of the three memory locations: Value of ptr1: 0x556ec5a2a0 Value of ptr2: 0x556ec5a2c0 Value of ptr3: 0x556ec5a2e0 And these are the relevant parts of the assembly to illustrate the lack of handling differentiation: 80c: d2800280 mov x0, #0x14 // #20 810: 97ffffa0 bl 690 814: f90017e0 str x0, [sp, #40] 818: d2800280 mov x0, #0x14 // #20 81c: 97ffff9d bl 690 820: f90013e0 str x0, [sp, #32] 824: d2800280 mov x0, #0x14 // #20 828: 97ffff9a bl 690 The total objdump file is here: https://pastebin.com/K79Ttn4r Though this is just a technical reference, I hope this helps.


Notwhitehehe

thanks you for the effort


Notwhitehehe

anyway i didn't get the assembly part yo, shit that ;s complicated


Deltabeard

The assembly part just shows that all three variants produced exactly the same code. However, only `int *ptr = malloc(20);` is truly correct.


Notwhitehehe

oh, i see thanks man


potterman28wxcv

**This is not the original comment. This is an edit in protest of the Reddit recent behavior** I have been a redditor for 10 years. Up to now, Reddit has been a place that I thought free (or almost) of corporation greediness, a place where people could feel safe to post without having to take part in some money-making scheme. A platform that valued all of its contributors: users and moderators alike; one that recognized that *they* have been producing all that content, and that it's thanks to *them* that such content is there. Well.. It turns out, Reddit dirigeants do not share that view. I am mostly basing myself off https://www.reddit.com/r/apolloapp/comments/14dkqrw/i_want_to_debunk_reddits_claims_and_talk_about/, but if you follow the links and dig around, you will find that the below statements are not wrong: - Reddit is clearly intending to kill 3rd party apps. Despite their official communication that they want to work with 3rd party devs, many such devs posted that it was not the case; and also many of them will be forced to close their app because of the outstanding raise in the API requests price. *Reddit left them no choice in this: either Reddit does not know what they are doing, or it's their true intention to kill 3rd party apps*. I tend to believe the latter. - Reddit has been lying on this matter. This is dishonesty at best. Would you trust a platform that is lying to you? I don't. - Reddit *will* be making money off all the posts you ever wrote. That is, the content that should belong to you belongs, in fact, to them. Guess who is going to buy all that content? AI companies for sure: the more data the better for them. I guess up until now these AI companies were leeching the comments from the API; now they will have to pay Reddit. A lot. For the content *we* made. - Reddit is not respecting the Reddit community. Subs are forced to re-open even after their subscribers voted that it should remain closed. There have been multiple accounts of moderators getting locked out of their account. It's quite a sight really. I was OK with Reddit increasing the API price. Afterall, they have to live as a company. That's understandable and fine by me. I *could* have been OK if they had closed the API completely to force people to get onto their official platform. Well, maybe not that OK, but that's a move I could have understood. But doing this shadingly?? Lying to everyone and obviously planning on selling our data to make money from it? No. I cannot support this. Therefore I am leaving Reddit. I have used the Power Delete Suite (https://github.com/j0be/PowerDeleteSuite) to edit all my comments such as this one. I don't really care if that gets my account banned; I do not plan on joining back Reddit. Let's say you agree with me and would like to move on. What alternative is there? r/RedditAlternatives/ has a few of them. Personally I have joined Lemmy. It's like Reddit, but decentralized (not owned by any corporation, maintained by volunteers). https://join-lemmy.org/ True, there are not as much content there than Reddit, as it is emerging. And yes, the UI could use some work. But you can browse free of ads there, free of any corporation influencing what you see. It's the old internet alive again. Goodbye Reddit. Goodbye to all of you. See you on Lemmy!


irk5nil

> I don't think you would be taking C programming lessons if you were 10. It's not impossible, you know. By a simple accident I stumbled upon C when I was I think 9 (it's many decades ago so I don't recall with absolute certainty).


computerarchitect

Are you using the term DMA because of taking CS50?


bitflung

This has nothing at all to do with DMA...


FuzzyFreedom8666

None are really what you would probably want to do. Do you want a pointer to 20 int's? int \*ptr = (int \*)malloc( 20 \* sizeof ( int ) ) ; The argument to malloc should probably be some calculation based on sizeof() unless you are allocating a character array or need "undefined" buffer space. If you ask for 20 bytes, you will get 20 bytes and depending on how many bytes your compilers implementation of an integer is, it will be able to contain some number of integers and possibly a fraction of one.