Scott.D
Scott.D

Reputation: 79

C malloc a pointer multiple times

If I have a pointer: char ** tmp = (char **)malloc(sizeof(char *) * MAX_SIZE), after assigning values to each block, I have a new pointer char ** ptr = tmp.

1). Can I tmp = (char **)malloc(sizeof(char *) * MAX_SIZE) malloc it again without free it?

2). Does the ptr still has the values and also tmp points to a new block of memory?

I have a function to free all used memory at the end, so don't worry about free.

Upvotes: 3

Views: 744

Answers (4)

Z1NZ
Z1NZ

Reputation: 1

int main(int argc, char **argv) {

    tmp = (char**)malloc(sizeof(char*) * argc);
    while (argv[i])
    {
        tmp[i] = strdup(argv[i]);
        i++;
    }
    if (argc > 3)
       printf("%s", argv[2])
    return(0)}

Upvotes: 0

rpy
rpy

Reputation: 4013

Assigning tmp to ptr keeps a reference to the malloced memory area. So re-assigning tmp using a new call to malloc is not a problem. This will not loose reference to the malloced memory as ptr is an existing alias.

So

  1. yes, you can do another malloc. (You could do anyway, but would loose reference to malloced memory)

  2. Yes, ptr still references the malloced area

BTW, doing a free at the end could be rather pointless if this would refer to at the end of the program. So, I assume you mean, at the end of the current algorithm.

Anyway, you need to keep references to the allocated memory. Usually it is advisable to release such memory as soon as it is no longer used.

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281646

malloc is used to allocate a memory block. It allocates a block of memory of provided size and return a pointer to the beginning of the block.

So the first time you write

char ** tmp = (char **)malloc(sizeof(char *) * MAX_SIZE)

it allocates memory and return a pointer pointing to beginning of memory location to temp. Now when you assign tmp to ptr, ptr now points to the allocated memory along with tmp. Now again if you write tmp = (char **)malloc(sizeof(char *) * MAX_SIZE) it will allocate a new memory and return a pointer to which tmp will be pointing to. But ptr still continues to point to the previously allocated memory. So the answer to both of your question is YES.

I hope I was able to explain the things correctly.

Upvotes: 1

ameyCU
ameyCU

Reputation: 16607

1). Can I tmp = (char **)malloc(sizeof(char *) * MAX_SIZE) malloc it again without free it?

Yes , you can again allocate memory again . But tmp will now point to a new allocated memory and to previously allocated memory .

2). Does the ptr still has the values and also tmp points to a new block of memory?

Now tmp will point to newly allocated memory but ptr refers to the previous memory location which was allocated .

So in this way you don't loose reference to any of the memory block and can be freed .

Upvotes: 1

Related Questions