|
From: Luigi S. <gi...@li...> - 2001-06-24 17:44:30
|
Hello !
The small program that follows seems to be correct, with DEV it compiles and
executes successfully, but I have a few questions about it (see the comment)
test.c
-------
/*********************************************************************
Please answer these questions:
(suppose that argc is 1, so that the if will be executed)
- am I allowed to free argv (before the statement argv = new_argv)?
- at the end of the program. will anybody free argv (and the strings
pointed by its elements) for me?
- if nobody frees argv, will there be a "memory leak"?
- can a "memory leak" cause trouble?
*********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARGV0 "new_program_name"
#define ARGV1 "new_first_argument"
#define NEWARRAY(ptr, len, T) \
{ \
ptr = (T *)calloc(len, sizeof(T)); \
if (!ptr) \
{ \
fputs("out of memory\n", stderr); \
exit(EXIT_FAILURE); \
} \
}
#define NEWSTRING(ptr, len) \
NEWARRAY(ptr, len + 1, char)
char *
copy(const char *from); /* make a copy of FROM */
/********************************************************************/
int
main(int argc, char **argv)
{
if (argc == 1) /* change the argument list */
{
char **new_argv;
argc = 2;
NEWARRAY(new_argv, argc, char *); /* get memory for arg list */
new_argv[0] = copy(ARGV0);
new_argv[1] = copy(ARGV1);
free(argv); /* trouble ? */
argv = new_argv; /* who will free new_argv? */
}
puts("Here is the argument list:");
while (argc--)
puts(*argv++);
system("pause");
return EXIT_SUCCESS;
}
/*******************************************************************/
char *
copy(const char *from)
{
int len = strlen(from);
char *s;
NEWSTRING(s, len);
return strcpy(s, from);
}
-------
One last thing: is there any tool that catches memory leaks ?
Thank you for your time.
--
gisan
|