I
I
Ilkhomjon Matazimov2022-01-30 20:40:50
C++ / C#
Ilkhomjon Matazimov, 2022-01-30 20:40:50

How to clear the allocated address memory under the address of the pointer to the first element of the string?

It seems that I’m doing everything right, but for the 2nd day I’ve been racking my brains why I can’t free the allocated memory:

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

int	main(void)
{
  const char **text;
  const char *smth = "some";

  text = (const char**)malloc(sizeof(char*));
  if(NULL == text) return 0;

  text = &smth;
  printf("%s\n", text[0]);
  
  free(text);
  text = NULL;

  return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilhomjon Matazimov, 2022-01-30
@mr_qpdb

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

int	main(void)
{
  const char **text;
  const char *smth;
  
  smth = "some";

  text = (const char**)malloc(sizeof(char*));
  if(NULL == text) return 0;

  *text = smth;
  printf("%s\n", text[0]);
  
  free(text);
  text = NULL;

  return 0;
}

A
Adamos, 2022-01-30
@Adamos

// выделяется память размером с указатель (4/8 байт для x32/x64), ее адрес записывается в text
text = (const char**)malloc(sizeof(char*));
// в text записывается адрес другой строки, а где там была выделена память - больше никто не знает
text = &smth;
// освобождается та память, на которую указывает text - это переменная smth. Теперь память, в которой лежит эта переменная, может в любой момент быть заменена при новом выделении памяти, и smth получит новое значение, не имеющее никакого отношения к той строке, на которую оно указывало изначально
free(text);

E
Evgeny Zaletsky, 2022-01-30
@JZ_52

If memory serves, then you need delete[]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question