Go Down

Topic: Problem with malloc() (Read 1 time) previous topic - next topic

Vinicius

Hi,
I'm a beginner in programing with C and I'm having some problems with malloc. I dont know what is wrong in the following code:
Code: [Select]
void setup(){
int *vetorV;
vetorV =  malloc (40*sizeof(int));
}

void loop(){}

I keep geting the error mensage: "invalid conversion from 'void*' to 'int*'". I'm sorry if the answer to my question is to obvious, but I've already looked up in a lot of tutorials and related topics and couldn't find anything helpfull.
Thanks

RuggedCircuits

Try this:

Code: [Select]
vetorV = (int *) malloc(40*sizeof(int));

--
The Gadget Shield: accelerometer, RGB LED, IR transmit/receive, speaker, microphone, light sensor, potentiometer, pushbuttons

Vinicius

Thanks RuggedCircuits, but I had already tried that. Although the program would compile, it seems that it isn't working properly. When I try "sizeof(vectorV)", it always returns 2, no matter what the argument to malloc is. Loking up on the internet, I found this:
Code: [Select]
int *ptr;
ptr = malloc(10 * sizeof (int)); // Without a cast
ptr = (int*)malloc(10 * sizeof (int)); // With a cast

"Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found."
http://en.wikipedia.org/wiki/Malloc
I'm not sure that really is the problem, but even if it is, I undestood from other topics tha the stdlib.h is already included in any arduino program and I dont know how to fix it.
PS: I tried using "#include <stdlib.h>" at the beginning of the code, but it didn't make any difference.

RuggedCircuits

Quote
When I try "sizeof(vectorV)", it always returns 2, no matter what the argument to malloc is.


That's correct. sizeof(vectorV) is the size of an "int *" because that is the type of vectorV. An "int *" is an address, and on the AVR an address is 16 bits, or 2 bytes. So sizeof is correct.

If you are a beginner in C then you're playing in the wrong waters. Pointer programming and malloc() are considered "advanced" usage. I'd suggest looking at some of the many C programming tutorials on-line on pointers and make sure you understand those first. Then you can move on to malloc.

--
The DIN Rail Mount kit for Arduino: quickly attach your Arduino to standard DIN rail

Vinicius

Hey RuggedCircuits, thanks a lot!!! I hadn't considered that. I know that using malloc is quite complicated for beginners but, for what I need, I dont see any alternative rather than dynamically expand an array. Just one more thing: how can I be sure that I'm not trying to write on an unavailable memory space?

Go Up