You're not actually using malloc on the same pointer. You're not giving the pointer to malloc at all. malloc always allocates new memory. So, the same thing happens as is the case with any variable assignment:
int a; a = 14; a = 20;
What happens to the 14? You can't access it anymore. In terms of malloc this means you no longer have a reference to the pointer it returned, so you'll have a memory leak.
If you actually want to use "malloc with the same pointer", you might be interested in the realloc function:
int *newPtr; newPtr = malloc(10 * sizeof(int)); newPtr = realloc(newPtr, 10 * sizeof(int)); //*might leak memory*
From that link: realloc "changes the size of the memory block pointed to by ptr. The function may move the memory block to a new location (whose address is returned by the function)."
EDIT: Note that if realloc fails in the above, then it returns NULL, yet the memory pointed to by newPtr is not freed. Based on this answer, you could do this:
void *emalloc(size_t amt){ void *v = malloc(amt); if(!v) { fprintf(stderr, "out of mem\n"); exit(EXIT_FAILURE); } return v; } void *erealloc(void *oldPtr, size_t amt){ void *v = realloc(oldPtr, amt); if(!v) { fprintf(stderr, "out of mem\n"); exit(EXIT_FAILURE); } return v; }
and then:
int *newPtr; newPtr = emalloc(10 * sizeof(int)); newPtr = erealloc(newPtr, 10 * sizeof(int));
mallocreturns an address to where it allocated the memory as you requested.