[SOLVED] Allocated memory + memset

Posted By: Saturnus

[SOLVED] Allocated memory + memset - 01/01/09 01:05

Hello everybody,

I would like to use memset to initialize allocated memory to zero. However it does not work as expected.

Code:
#include <acknex.h> 
#include <default.c>

void main()
{
   // allocate memory for 100 integers
   int *array = (int *)malloc(100 * sizeof(int));
	
   // initialize memory
   memset(array, 0, 100 * sizeof(int));
	
   // display int #3 on the screen (should be zero, but isn't)
   error(str_for_num(NULL, *(array + 2)));
} 

In this example 'array' should be initialized to zero, but it isn't: It still contains random values.

What am I doing wrong here?

Thank you!
Posted By: Schmerzmittel

Re: Allocated memory + memset - 01/01/09 01:34

Probiers mal mit einer for-Schleife.
Gehe dabei jeden Array durch und setze ihn auf null.
Das hier müsste funktionieren. (Also in C++ auf jedenfall)

Code:
int array[100];

for(int iCurrentIndex = 0 ; iCurrentIndex < 100 ; iCurrentIndex++)
array[iCurrentIndex] = 0;
]

Ich frage mich nur, warum du überhaupt Speicher Reservieren willst. Du arbeites anscheinend mit Lite-C. Da wird der Speicher ja Dynamisch verwaltet, oder täusche ich mich da.
Posted By: Saturnus

Re: Allocated memory + memset - 01/01/09 02:14

Ja, for-Schleifen gehen auch. memset würde ich hier aber bevorzugen, weil ich annehme, dass memset schneller ist. : )

memset sollte in Lite-C funktionieren; jedenfalls habe ich Threads gefunden, in denen es benutzt wurde.

Quote:
Ich frage mich nur, warum du überhaupt Speicher Reservieren willst. Du arbeites anscheinend mit Lite-C. Da wird der Speicher ja Dynamisch verwaltet, oder täusche ich mich da.

Diese Speicherreservierung benötige ich für dynamische Arrays. Die Allokierung und Freigabe des Speichers passiert in Lite-C nicht automatisch.
Posted By: Davidus

Re: Allocated memory + memset - 01/01/09 02:52

I believe you expected C to set newly allocated memory/variables to be zero, but they aren't,
they contain the same value that has been stored in your RAM by other programs before - they can contain almost anything before they get a value.
Don't know, but in some languages arrays contain only NULL values until things are stored, so perhaps it's the same here.
The hint given to you by Painkiller ( laugh ) should work, i expect.
Posted By: Saturnus

Re: Allocated memory + memset - 01/01/09 03:30

Quote:
I believe you expected C to set newly allocated memory/variables to be zero

No, I do not expect the allocated memory to be initialized to zero automatically.
Thats why I want memset to do this. ; )

However, memset does not work in my example (first post).

Of course, I could use for loops as suggested by Schmerzmittel, but obviously memset is faster than for loops.
So I wourld prefer to get memset working properly. : )
Posted By: Petra

Re: Allocated memory + memset - 01/01/09 09:01

You're completely right and I had the same problem with my project! Only with hard looking in the online manual I found the solution.

"!! sizeof() is a macro and not a function. It can be used for setting a variable or passing a parameter to a function, but can not be used in expressions. Thus, long_size = sizeof(long); is ok, but long_size_times_ten = sizeof(long)*10; is not. "

http://manual.conitec.net/structs.htm


// allocate memory for 100 integers
int *array = (int *)malloc(100 * 4);

// initialize memory
memset(array, 0, 100 * 4);

Posted By: Saturnus

[SOLVED] Allocated memory + memset - 01/01/09 16:42

Petra, thank you! Now its working fine.

I dindn't know that sizeof can't be used in expressions in Lite-C. Probably I have to recheck some of my scripts due to this fact.

Schmerzmittel & Davidus, thank you too for your suggestions.
Posted By: EvilSOB

Re: [SOLVED] Allocated memory + memset - 01/02/09 20:48

Ive been using a workaround for some time that works fine for me.
Replace the line
Code:
int *array = (int *)malloc(100 * sizeof(int));
with
Code:
int *array = (int *)malloc((int)sizeof(int) * 100);

or if you wanted floats use
float *array = (float *)malloc((int)sizeof(float) * 100);
Putting the (int) in front of the sizeof() typecasts it into an integer and Ive found it then works fine in arithmetic.

If anyoneone wants to dis-agree, let me know as I may need to change a lot of my old coding...
Posted By: Saturnus

Re: [SOLVED] Allocated memory + memset - 01/03/09 18:50

@EvilSOB
Thank you for this info.
I have tested this workaraound with various data types and obviously its working fine indeed.
I wonder if one could use this without any risks?


BTW, does somebody know if memset can be used on only a part of an array (or other memory area) in lite-C?

I have tried the following:
Code:
// presumption: array length: 50, type: int

// initialize second half of array to zero
memset(array + 25, 0, 24 * 4);
// memset(&array[25], 0, 24 * 4); // alternative way

But this does not work. I guess its not possible to receive an address with address operators or in another way in lite-C?
Posted By: EvilSOB

Re: [SOLVED] Allocated memory + memset - 01/03/09 20:23

I use it all the time and have had no problems in over a year, which
is only development projects so far, no ACTUAL games as yet. But I
use it a lot with large arrays as Im trying to work out some Entity
swarm logic processes for creating dynamic/reactive asteroid fields.

Dunno about memset problem, but try this one
memset(&(array[25]), 0, 24 * 4);


[EDIT]
This one works for me. Tested with the array defined as
var* array = (var*)malloc((int)sizeof(var)*50);
memset(array[25], 0, 24 * 4);

Posted By: Saturnus

Re: [SOLVED] Allocated memory + memset - 01/03/09 22:37

Quote:
This one works for me. Tested with the array defined as
var* array = (var*)malloc((int)sizeof(var)*50);
memset(array[25], 0, 24 * 4);

I have tested this before with an int array. But for some reason it does not work with int arrays ("crash in main", although i am pretty sure it did not crash in the first place, but resulted in an uninitialized array).
However, with var (and other data types such as float and short) there aren't any problems indeed.
Well, I don't really know why. : )

Thank you for pointing this out.
Posted By: EvilSOB

Re: [SOLVED] Allocated memory + memset - 01/04/09 00:05

Hmm, yes. Rather odd. I wonder why int's are handled differently?
Anyway, I testad a bit and came up with this that appears to work OK.
The one memset line is the important line you are after, and the rest is there
so you can see it in action, based on your original post in this thread.

As usual, any question or problems, just ask...
Code:
   // allocate memory for 100 integers
   int* array = (int*)malloc( (int)sizeof(int) * 100 );
   
   // initialize memory to 5's
   int i; for(i=0; i<100; i++) array[i]=5;
   
   // display int #11 on the screen (should be five)
   error(str_for_num(NULL, array[10] ));
   
   // display int #61 on the screen (should also be five)
   error(str_for_num(NULL, array[60] ));
   
   //reset elements 50-100 to zero
   memset(&(array[50]), 0, ((int)sizeof(int) * 50) );
   
   // display int #11 on the screen (should still be five)
   error(str_for_num(NULL, array[10] ));
   
   // display int #61 on the screen (should now be zero)
   error(str_for_num(NULL, array[60] ));
   
   //clean up when done
   free(array);

Posted By: Saturnus

Re: [SOLVED] Allocated memory + memset - 01/06/09 08:26

In this case I will stay with a for loop initialization, I think. However, I still have to check if a simple memset(array[25]...) works with my struct pointers.
I needed this for indexing the elements of a heap. When elements are added to the heap, the indexing array is reallocated if necessary. Then only a part of the array needs to be initialized. This is a rare case though, so a simple loop should do the job too. : )

Thanks for your effort.

// Edit
FYI: http://www.opserver.de/ubb7/ubbthreads.php?ubb=showflat&Number=244692#Post244692
Posted By: EvilSOB

Re: [SOLVED] Allocated memory + memset - 01/07/09 02:24

no problem, and thanks for the fyi
© 2024 lite-C Forums