I've initialized a char** and allocated space using malloc in a loop
char *argv[SIZE];
for( i=0 ; i < SIZE; i++ ){
argv[i] = (char *) malloc(64);
printf("ADDRESS %d Index %d\n",argv[i],i);
}
the printf shows addresses going up by 160, instead of 64, is that normal?
and lets say I pointed second index to null
argv[1] = NULL;
they I try to make it point to its allocated memory location by
argv[1] = arg[0] + 64;
which crashes the program after I try to free in loop
free(argv[i]);
so how can I make it point to its original location? where does the 160 come from?
thanks in advance
Never, ever assume that two blocks of allocated memory should "normally" be adjacent in memory. There may be allocator "bookkeeping" data attached to them; they may be padded to align at certain block sizes for efficency; they may be using previously-allocated memory at all sorts of random locations.
When you say:
argv[1] = arg[0] + 64;
You may as well say:
argv[1] = arg[0] + 1234534321;
That's just as likely to be correct. If you want to restore argv[1]
to its original value, save that value first, don't guess where it might be.
char *saveArgv1 = argv[1];
argv[1] = NULL;
argv[1] = saveArgv1; /* now it's back to its old self */