Home > Software design >  ANSI C - Why malloc and free dont work for char pointers?
ANSI C - Why malloc and free dont work for char pointers?

Time:01-17

When I try to run this code:

char *s;
s = (char *) malloc (15);
s = "hello world";
free(s);

using gcc ts.c -ansi -Wall the result is:

free(): invalid pointer
Aborted (core dumped)

and the warning is:

‘free’ called on a pointer to an unallocated object 

I don't understand why char pointers are different from other pointers.

CodePudding user response:

This code snippet

char *s;
s = (char *) malloc (15);
s = "hello world";

produces a memory leak.

At first a memory was dynamically allocated and its address was assigned to the pointer s

s = (char *) malloc (15);

and then the pointer s was reassigned with the address of the first character of a string literal

s = "hello world";

In fact the above statement is equivalent to

s = &"hello world"[0];

String literals have static storage duration. So you may not apply the function free for string literals.

Instead of this assignment

s = "hello world";

you need to use the standard string function strcpy declared in the header <string.h>

#include <string.h>

//...

strcpy( s, "hello world" );
  •  Tags:  
  • Related