-1

I'm currently working on CS50's Lab 4 - Volume. I have the following code and I'm wondering if it's okay to use the same pointer name in two separate places after calling free on it.

 //Initialize tmp pointer and copy header bytes from input to output file
uint8_t *tmp = malloc(sizeof(uint8_t));
if (*tmp == NULL)
{
    printf("Mem_ERR_2\n");
    return 2;
}

for (int b = 0; b < 44; b++)
{
    *tmp = fgetc(*input);
    *output = fputc(*tmp);
    printf("H_BYTE = %i\n", b++);
}

free(*tmp);

I have *tmp initialized, dereferenced it, and now I'm calling free on it. After this I want to create a second *tmp pointer for a different part of code. My question is, it it good practice, or even syntactically okay to initialize uint16_t *tmp for a second pointer? Or should I change them to *tmp1 and *tmp2?

0x4a6f7368
  • 38
  • 6
  • 1
    Does this answer your question? [Best practices to avoid problems with pointers](https://stackoverflow.com/questions/1432963/best-practices-to-avoid-problems-with-pointers) – Danilo Mercado Oudalova Oct 19 '21 at 02:55
  • 1
    Syntactically I'd assume not (differing types, redeclaration of a variable, etc.), but as far as "good practice" I'd be in the "no" camp. Try thinking of a more relevant variable name than `tmp`. – Rogue Oct 19 '21 at 02:55
  • Ok, I sort of was thinking that, but I wanted to get some opinions. As far as the linked post, I didn't really see what I was looking for specifically, but I didn't dig through everything. I will definitely look through that post because there looks like some good info. – 0x4a6f7368 Oct 19 '21 at 03:03

1 Answers1

0

To begin with, the line *tmp == NULL is a bug. If malloc fails and returns NULL, then evaluating the expression *tmp will cause a segmentation fault. Instead, try tmp == NULL. This also means that free(*tmp) is a bug - it should be free(tmp) instead.

Now, to answer your question: It is perfectly fine to reassign a pointer variable after it has been freed. For example, the following is perfectly valid:

int * ptr = malloc(16);
free(ptr);

int x = 5;
ptr = &x;

ptr = malloc(16);
free(ptr);
squidwardsface
  • 389
  • 1
  • 7