amIllusionist
amIllusionist

Reputation: 142

how can I fix this error when allocating memory?

the code below has an error please help me how can I fix it. I'm beginner in C++.

int main(int    argc,   char    **argv)
{
image=malloc(3*1450*900*sizeof(char));      /*  to  ALLOCATE    MEMORY  required    to  SAVE    the file    */
    some thing else....}

The error is: a value of type "void*" cannot be assigned to an entity of type "char*"

Upvotes: 2

Views: 438

Answers (4)

0bijan mortazavi
0bijan mortazavi

Reputation: 368

it's clear as you see in error report! you should cast every thing at the other side of "=" operator to (char*)!

image=(char*)malloc(3*1450*900*sizeof(char));

Upvotes: 1

Ralph Tandetzky
Ralph Tandetzky

Reputation: 23610

Why it doesn't work and a quick fix

The reason your code doesn't work is, that malloc() returns a void* which cannot be implicitly converted to a char*. Therefore, it is said that malloc() is not type-safe. You can cast the returned pointer explicitly by writing (char*)malloc(3*1450*900) but this is kinda ugly. (BTW sizeof(char) is always 1.)

A more modern approach

In modern C++ you should do memory allocations using containers like std::vector<T>. Also: try to avoid global variables outside functions and classes. Here's what I would write:

int main()
{
    std::vector<char> image( 3*1450*900 ); // automatically fills with zeros.
}

This has the advantage, that memory management is done automatically. The allocated memory will be freed when the image object is destroyed.

Upvotes: 4

Danny_ds
Danny_ds

Reputation: 11406

First, In C++ you should be using new / new[] and delete / delete[] instead of malloc().

An even better way would be to use std::vector: std::vector<char> image(3*1450*900);


If you really would need to use malloc() in C++, you need to cast the return value (malloc() returns a void*):

image = (char*)malloc(3*1450*900*sizeof(char));

And of course, always check the return value before continuing.

Upvotes: 5

Score_Under
Score_Under

Reputation: 1216

Since you're using C++, you should instead be creating your arrays with new[] and deleting them with delete[].

int main(int argc, char **argv)
{
    image = new char[3 * 1450 * 900];
    // ... some code here? ...
    // When you're finished with image:
    delete[] image;
    // ... some code here? ...
    return 0;
}

You don't need sizeof if you're using the new[] or new operators, but even so, I want to mention that sizeof(char) is always equal to 1.

If you are using C++11 (you should be!), then it might be more appropriate to declare image as a unique_ptr<char[]> to prevent memory leaks caused by improper exception handling or simply forgetting the delete[].

Upvotes: 2

Related Questions