#define LINE_LEN 80
#define MAX_ARGS 64
#define MAX_ARG_LEN 64
#define MAX_PATHS 64
#define MAX_PATH_LEN 96
#ifndef NULL
#define NULL 0
#endif
...
struct command_t {
char *name;
int argc;
char *argv[MAX_ARGS];
};
...
/* Command initialisation, allocate type command */
struct command_t command;
command.name = (char *) malloc(LINE_LEN);
command.argc = 0;
for(ii=0; ii < MAX_ARGS; ii++) { /* i < 64 */
command.argv[ii] = (char *) malloc(MAX_ARG_LEN);
}
...pass in some values in command.argv, I have something like command.argv[0] = "man", and command.argv[1] = "socket", command.argc = 2, command.name = "name" for example like this
command.name = "man"
command.argc = 2
command.argv[0] = "man"
command.argv[1] = "socket"
command.argv[2] = ""
command.argv[3] = ""
...
command.argv[63] = ""
then the question is when I did below:
char *argTemp[command.argc+1];
for(ii = 0; ii < command.argc+1; ii++){
if(strlen(command.argv[ii])){
argTemp[ii] = (char *)malloc(strlen(command.argv[ii])+1); /*added +1*/
/* argTemp[ii] = command.argv[ii]; */
/*delete the line above, problem still exist*/
strcpy(argTemp[ii], command.argv[ii]);
} else {
argTemp[ii] = (char*)NULL;
}
}
The memory allocation for command was successful, everything works for command. however, when using the same technique for argTemp[], in the debugger, I see argTemp is [0], there is nothing in it, nor it points to anything. I don't understand why? I'm expecting to see artTemp[] to be the same as command.argv[], only getting rid of the extra null memory. like this:
argTemp[0] = "man"
argTemp[1] = "socket"
argTemp[3] = "\000"
and that is, no more argTemp, then i will free command.argv, and point command.argv to argTemp. So you probably see all I'm trying to do here is to get rid of the memory with null value in command.argv.
NULLshould be((void *)0)for correctness on platforms wheresizeof(int) != sizeof(void *)(it can cause problems when used in varargs functions, which don't know to implicitly cast the 0 to aNULLpointer).