Good day. There was the following problem. The following code is available:

int leng[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int *res; res = (int*)malloc(8*sizeof(int)); // на 8 не обращайте внимание memset(res, 0 , 8); res = func(leng, 10, 8); // ... 

Here is the code of the func function itself:

 static int* func(int *arr, int len, int size) { int *arrTemp; int i = 0; arrTemp = (int*)malloc(len* sizeof(int)); memset(arrTemp , 0, len); for (i = 0; i < length; i++) printf("%d ", *(arrtemp + i)); // ... } 

On the screen when printing the first three elements as in the original array, the rest is garbage. Help me figure out why?

  • one
    You do not need to correct the code in question for the worker, after you have been answered and pointed out errors. Otherwise, people who come here later will not understand what the problem was originally. - zed
  • Thank you very much for the comment! I will consider - Setplus

2 answers 2

memset installs the specified number of bytes . If you want to reset everything - pass the full size, as in malloc :

 arrTemp = (int*)malloc(len* sizeof(int)); memset(arrTemp , 0, len* sizeof(int)); 

the pointer passed to func is not used anywhere at all. So you deduce zero and a little garbage.

Unless, of course, you wrote the code that really is. What allow me to doubt - for example, in

 for (i = 0; i < length; i++) 

what is length ? You do not have this variable.

  • Thank you very much for the comment! length corrected (it was from the old file). - Setplus
  • the answer then to the question "why is there rubbish?" - because you need to specify everywhere size * sizeof (int) - to specify the byte? (size in this case is an abstract constant). - Setplus
  • 2
    calloc() = x = malloc(n * sizeof(*x)); memset(x, 0, ...); x = malloc(n * sizeof(*x)); memset(x, 0, ...); - 0andriy

Everything works absolutely fine:

  #include <stdio.h> #include <stdlib.h> #include <string.h> static int* func(int *arr, int len, int size) { int *arrTemp; int i = 0; arrTemp = (int*)malloc(len* sizeof(int)); memset(arrTemp , 0, len * sizeof(int)); memcpy(arrTemp, arr, len * sizeof(int)); for (i = 0; i < len; i++) printf("%d ", *(arrTemp + i)); return arrTemp; } int main () { int leng[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int *res; res = (int*)malloc(8*sizeof(int)); // на 8 не обращайте внимание memset(res, 0 , 8*sizeof(int)); res = func(leng, 10, 8); } 
  • Just for some reason, the topstarter fixed the code in question for the worker, after he received the answer. I rolled back the corrections of the code in the question. - zed
  • Thank you very much. Yes, it was already a dream affair, so, apparently, by mistake, I introduced unnecessary corrections :) - Setplus