Archived

This topic is now archived and is closed to further replies.

Dynamic memory allocation of arrayed char

This topic is 5570 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m having problems allocating memory for an array of strings. Here''s my code: (char **val1 = NULL and char **val2 = NULL exist). There seems to be a problem as to where the pointers are pointing in memory since val1 sometimes returns the content of val2. Thanks for any help in advanced. char **tmpval1; if((tmpval1 = (char**)realloc(val1, size*sizeof(char))) == NULL) { return ERROR_MEM; } val1 = tmpval1; char **tmpval2; if((tmpval2 = (char**)realloc(val2, size*sizeof(char))) == NULL) { return ERROR_MEM; } val2 = tmpval2;

Share this post


Link to post
Share on other sites
Assuming your strings are standard C strings (array of char''s) and size is the number of strings in your array...

tmpval1 should point to an array of char*''s and your not allocating enough memory for this. The amount of memory allocated should be size*sizeof(char*)

Share this post


Link to post
Share on other sites
Thanks sizeof(char*) was the problem that caused the crash.

I have another problem when i copy memory into my newly allocated memory.

demonstration code:
CString astring;
astring = "text";
val1[0] = memcpy(val1, astring, astring.GetLength());
astring = "another text";
val1[1] = memcpy(val1, astring, astring.GetLength());

calling memcpy the first time is fine the second time it doesnt copy the data correctly.
Do you have any idea what the problem could be?





Share this post


Link to post
Share on other sites
You''ve allocated memory for the array but not the strings. val1[0] ... val1[size-1] are undefined pointers.
Try..


  
for(int i=0;i<size;i++)
val1[i] = new char[SomeStringSize];


Then do the copy. Also, look at these lines:


  
val1[0] = memcpy(val1, astring, astring.GetLength());
val1[1] = memcpy(val1, astring, astring.GetLength());


The first parameter (destination) of memcpy should be val1[0] and val1[1], respectively. NOT val1. Left as written you''ll overwrite the pointers in the array val1 with the string data.


Share this post


Link to post
Share on other sites
quote:
Original post by Solo
You''ve allocated memory for the array but not the strings. val1[0] ... val1[size-1] are undefined pointers.

(..)

The first parameter (destination) of memcpy should be val1[0] and val1[1], respectively. NOT val1. Left as written you''ll overwrite the pointers in the array val1 with the string data.





Thank you very much! You solved my problem.


Share this post


Link to post
Share on other sites