This assignment in the server code is not doing what you want:
Array[ArrayCount] = revdData;
This is invalid code, because revdData
is a local array with scope delimited to server()
. The assignment doesn't copy the array, it copies the pointer to its first element. So, by the time you return from server()
, Array
contains a pointer to an invalid location - the memory for the local revdData
array is invalid. What happens next is unknown. Usually, since you'll be calling server()
again, it is very likely that the same memory space is being reused for the new revdData
array, so it ends up overwriting what you don't want.
To fix it, you must either allocate memory in Array[ArrayCount]
and then use strncpy
, or use strndup
.
Here's what you can do with strncpy
:
Array[ArrayCount] = malloc(ns);
strncpy(Array[ArrayCount], revdData, (size_t) ns);
Also, you can change ns
from int
to ssize_t
, which is the return type of recv
.
If you want to use strndup
, you don't need to explicitly use malloc
, however, if your data contains null bytes, it will not copy beyond that point, and if it doesn't, it will add a null byte in the duplicated string, which might not be what you want.
Note that this approach introduces the problem of memory management; at some point, you have to free the memory allocated for each position taken in Array
. You are responsible for doing this, although in small programs you can usually rely on the fact that all allocated memory is freed by the operating system upon program termination.