Re: char* pname = "Harry"
- From: "John Bode" <john_bode@xxxxxxxxxxx>
- Date: 18 Apr 2006 04:55:11 -0700
erktek@xxxxxxxxx wrote:
Statement given below;
char * p ;
p = (char*) malloc(20);
Lose the cast, unless you're working with a *very* old implementation
(pre-C89).
p = "harry" ; // <------------- Is it perfectly valid ?
Perfectly valid, but not correct, given the context. Instead of
copying the contents of the string "harry" to the memory pointed to by
p, you've assigned the address of the string literal "harry" to p,
causing you to lose track of the memory you just allocated, which is a
memory leak.
Try
strcpy(p, "harry");
instead. Don't forget to #include <string.h>.
free(p);
This will attempt to free the string literal "harry", not the memory
you allocated earlier.
.
- Follow-Ups:
- Re: char* pname = "Harry"
- From: Jack Klein
- Re: char* pname = "Harry"
- From: Simon Biber
- Re: char* pname = "Harry"
- From: peter . koch . larsen
- Re: char* pname = "Harry"
- References:
- char* pname = "Harry"
- From: erktek
- char* pname = "Harry"
- Prev by Date: Re: OT Re: char string
- Next by Date: Re: Comparison function in qsort()
- Previous by thread: Re: char* pname = "Harry"
- Next by thread: Re: char* pname = "Harry"
- Index(es):
Relevant Pages
|