Reputation: 13
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
Upvotes: 1
Views: 1151
Reputation: 1042
For your use, you should consider a static memory allocation. On dynamic allocation, you cannot make the same assumptions. Also, when printing memory addresses, you may find it easier to read the values in hexadecimal. If so, then use %p in place of %d.
#include <stdio.h>
#define SIZE 10
static char argv[SIZE][64];
int main()
{
int i;
for( i=0 ; i < SIZE; i++ ){
printf("ADDRESS %p Index %d\n",argv[i],i);
}
return 0;
}
Upvotes: 1
Reputation: 36448
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 */
Upvotes: 1