Originally Posted by
MAtkins
In the code below, is there any way to deallocate the memory of buff1 after I've copied all but the first 5 characters to buff2?
Yes. Place the lines in their own block. Local variables (or arrays) cease to exist when they pass out of scope. You will need to reorder things if you want buff2 to subsequently exist though.
Code:
int main()
{
char buff2[4096];
{ /* start a new block */
char buff1[4096]="http://www.softlinksys.com/Programming/aspnet.php";
strcpy(buff2, buff1 + 5);
} /* close the block. buff1 ceases to exist, as far as your code is concerned */
/* do something with buff2
return 0;
}
Originally Posted by
MAtkins
Also, is there anything I can do to truncate the allocated memory to only what I need for buff2?
That depends on what you mean by "truncate". strlen() will report strlen(buff2) is of the length you intend. However, the buff2 will still consume 4096 bytes of memory.
If by "truncate" you mean "shorten the allocated length to no more than necessary", you can use dynamic memory allocation
Code:
char *buff2;
/* and later .... */
buff2 = malloc(strlen(buff1) + 1); /* +1 allows for terminating nul character */
strcpy(buff2, buff1);
of course, you have to remember to free(buff2) when you no longer need it, in order to avoid a memory leak.
Incidentally, when creating buff1, you are initializing with a string literal, so there is no need to specify a length of 4096. Instead you can do
Code:
char buff1[]="http://www.softlinksys.com/Programming/aspnet.php";
strcpy(buff2, buff1 + 5);
There are a few more devious tricks, but I'll stay quiet on those.