Re: char* pname = "Harry"




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.

.



Relevant Pages

  • Re: Segmentation fault
    ... Here you ask for a pointer to char. ... to a random position in memory. ... There's nothing else than a string the user could enter;-) ... to the use of scanf(). ...
    (comp.lang.c)
  • Re: Lilys profession
    ... but assuming that whatever Harry does ... James battled Voldemort for 5 minutes. ... memories which Snape safeguarded from Harry. ... Then why is OWLs End called the worst memory? ...
    (alt.fan.harry-potter)
  • Re: =?iso-8859-1?q?Re:_Snape=B9s_Overlooked_Memory?=
    ... >Green-Eyed Chris wrote: ... >>>have recognised Lily in Snape's memory? ... We do not know from what angle Harry is viewing ... It's the Weasleys who have flaming red hair. ...
    (alt.fan.harry-potter)
  • Re: Lilys profession
    ... Harry has recalled the same scene twice in canon, ... I've never put much stock in the exact memory. ... James battled Voldemort for 5 minutes. ... The *bad word*, IMHO, came from his calculating mind, ...
    (alt.fan.harry-potter)
  • Re: Lilys profession
    ... watch in the time Harry could penetrate his mind. ... "Snape's Worst Memory". ... but Harry didn't visit it before he got caught. ... Snape dropped a number of silvery strands ...
    (alt.fan.harry-potter)