Search code examples
carrayssocketspointerscalloc

Recieving C socket data to allocated 2D array


I am trying to populate an array I allocated with data recieved from a socket, but am unable to make it work properly. When i define and get data through:

uint16_t data[2048];
recv(network_socket, &data, sizeof(data), 0);

the data is recieved properly, but when I try to do it through an allocated array:

int i;
int N = 3;
int M = 2048;
int **matrix; 

matrix = (int **)calloc(N, sizeof(int *));

for (i=0; i<N; i++) {
    matrix[i] = (int *)calloc(M, sizeof(uint16_t));
}

for (i=0; i<N; i++) {
    recv(network_socket, matrix[i], sizeof(data), 0);
}

I am sensing things go wrong at the final part. As far as I understand matrix[i] at the end gets the pointer to the beginning of row i and should work for recv() but that might be where I'm going wrong here.

EDIT: When I try to printf("Number: %" PRIu16 "\n", matrix[a][b]); I get some whacko large number in the second part, wheras printf("Number: %" PRIu16 "\n", data[a]); works fine in the first.


Solution

  • You tell in your first code you want an array of 16bit unsigned integers and receive them. All is good.

    In your second code you want an array of ints which probably aren’t 16bit on your platform. Then you allocate an amount of memory to them based on them being 16bit values and read an undisclosed amount of data in.

    Then you try to access them as ints which obviously will cause two uint16_t values being combined into one int if your system is 32bit, or even four on a 64bit system.

    Fix your code to use uint16_t as in the first one and it’ll actually know how to handle the 16bit data. Your current code will even have undefined behavior since you try to access memory outside the allocated range.