Answer the question
In order to leave comments, you need to log in
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
#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;
}
// выделяется память размером с указатель (4/8 байт для x32/x64), ее адрес записывается в text
text = (const char**)malloc(sizeof(char*));
// в text записывается адрес другой строки, а где там была выделена память - больше никто не знает
text = &smth;
// освобождается та память, на которую указывает text - это переменная smth. Теперь память, в которой лежит эта переменная, может в любой момент быть заменена при новом выделении памяти, и smth получит новое значение, не имеющее никакого отношения к той строке, на которую оно указывало изначально
free(text);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question