Problem with malloc?

Hello, I use malloc () to create such a buffer, where buffer is char *

buffer = (char*)malloc(chunksize+1);
  for (k = 0; k < chunksize; k++) {
    buffer[k] = (char) (j+k);
  }

however, in the debugger I see a buffer [3], for example, it is char i, but the buffer is empty (many spaces). But the second time I write the material in the buffer after the free (buffer), it shows the contents that I wrote for the first time, and overwrites it. Can someone tell me why? Thank!

+3
source share
3 answers

Perhaps the problem is that you are trying to print a buffer charusing printfor equivalent? You are lacking

buffer[chunksize] = 0;

Thus, your buffer is not terminated. It may have something behind, for example '\r'.

, , buffer , , , unsigned char.

+1

, malloc , , . , .

malloc ( 0 ). , .

, malloc , . , ( , POV ).

, , malloced . "" , malloc , , .

"" , malloc , - ​​ .

, , . malloc, malloc , . , , , - "" , .

+8

. , , , - . , char, , , ( ). :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
  const size_t chunksize = 15;
  size_t k;
  char *buffer;

  buffer = malloc (chunksize + 1);
  memset (buffer, 0, chunksize + 1);

  for (k = 0; k < chunksize; ++k)
    {
      buffer[k] = '0' + (char)k + 49;
    }

  for (k = 0; k < chunksize; ++k)
    {
      printf ("%lu = %c\n", k, buffer[k]);
    }

  free (buffer);

  return 0;
}

:

0 = a
1 = b
2 = c
3 = d
4 = e
5 = f
6 = g
7 = h
8 = i
9 = j
10 = k
11 = l
12 = m
13 = n
14 = o
0

Source: https://habr.com/ru/post/1794224/


All Articles