This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

realloc() method

 
Parag Mokal
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everybody,
I've Red Hat Linix installed on my machine. I've problem with the realloc(void *p, size_t size) method in C. Here's the code
<CODE>
char *p;
p = (char *)malloc(sizeof("computer"));
strcpy(p,"computer");
printf("%s \n",p);
p = (char *)realloc(p,sizeof("computerization"));
printf("%s \n",p);
</CODE>
After running the program, the first printf prints word "computer", but on the second line I get the error
segmentation fault (core dumped)
The realloc method just doesn't work. The same code works at my institute. Can anyone help me with this?
 
Roseanne Zhang
Ranch Hand
Posts: 1953
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Parag Mokal:
<CODE>
p = (char *)malloc(sizeof("computer"));
...
p = (char *)realloc(p,sizeof("computerization"));
</CODE>

Compare these two lines, you should see the problem. You try to realloc a smaller memory allocated to become larger, it should report a fragmentation error. Your old machine is simply more tolerant than the new one, the new one is better.
You can free the old one, and alloc a new one instead.

JavaChina has been moved to
http://javachina.developergroup.org/

 
Parag Mokal
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I had to free the memory and use it, I would've used the malloc method only. The purpose of the realloc() method is to change the already allocated memory and this code runs fine on the machine in my institute. I've Redhat Linux 7.0 installed. The problem is still not clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic