Dynamic memory allocation of arrayed char

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;

This is an OpenGL forum, and not a forum for beginning ANSI C programming. Get a good ANSI C book and read up on how to use realloc and how strings are handled in C.

[This message has been edited by Asgard (edited 09-10-2002).]

I can see two mistakes in that code. First, sizeof(char) should rather be sizeof(char *) if I understand the purpose of the code right. Second, the tempval pointers are useless, assign to the val pointers directly.

Originally posted by Humus:
I can see two mistakes in that code. First, sizeof(char) should rather be sizeof(char *)

Thank you the sizeof(char*) was the problem.
i use the tmpval to avid memory leaks.

But now i have another problem conserning 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?

Get a C or C++ language reference text. Read the section on pointers and arrays VERY CAREFULLY. Don’t start writing code until you understand those sections well.