Freeing Strings in C

If I wrote:

char *a=malloc(sizeof(char)*4);
a="abc";
char *b="abc";

Do I need to free this memory, or is it done by my system?

+5
source share
6 answers

In your situation, you will have no way to free dynamically allocated memory, because you lose the link to it.

Try the following:

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

int main()
{
  char *a=(char*)malloc(sizeof(char)*4);
  printf("Before: %p\n",a);
  a = "abc";
  printf("After: %p\n",a);
  free(a);
  char *b = "abc";

  return 0;
}

You'll get

Before: 0x100100080
After: 0x100000f50

You will see that the two pointers are different from each other. This is because the string literal "abc"is placed in the binary data sector and when you execute

a = "abc"

a "abc", . free on a , , . ,

strncpy(a, "abc", 4)

, .

+10

. a="abc", , , "abc". b .

strncpy(a, "abc", 4), "abc" ( a ).

, .

+4

C

a = "abc"

, malloc, free,

free(a);

, free(a) , . malloc a "abc"; , free(a) . .

+3

: , . .

:

char *a=malloc(sizeof(char)*4);

, .

a="abc";

This assigns a pointer to a constant string to yours char* a, thus you lose a pointer to the memory allocated in the first line, you should never free constant lines.

Use strcpy(a,"abc");instead a="abc";to move the line to the allocated memory.

+2
source

yes, you need to free the memory returned by malloc.

0
source

Yes, it will cause a memory leak. The system could not handle this case.

0
source

All Articles