Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this bad practice? Redirect pointer pointing to blank string to another string?

Consider this snippet,

char *p1="";
printf("p1=%p\np1=%s\n",p1,p1);

char s1[6]="abcde";
printf("s1=%p\ns1=%s\n",s1,s1);

p1=s1;

printf("p1=%p\np1=%s\n",p1,p1);

Since, none of the variables are allocated on heap, all allocated space will be freed at the end of process.

Questions:

  • What happens to the blank string when the pointer pointing to it is redirected to another string? (As per my basic Java knowledge, incase of Java the blank string will be eligible for GC to be collected. What happens here?)
  • In case the code was longer, will the blank string utilise memory unecessarily till the end?
  • Valgrind does not report memory leaks (i guess this refers to heap memory only? ). Is there a scenario where such coding practise cause a bottleneck?
like image 228
Suvarna Pattayil Avatar asked Dec 26 '22 08:12

Suvarna Pattayil


1 Answers

Your strings "" and "abcde" live in the (read-only) data section of your executable. They are loaded into memory when your program is loaded.

When no more pointers point to it, then no more pointers point to it. That's all.

Programs have lots of read-only data (for example, the entire program's code!) It's not really something to be concerned with.

This is not considered a memory leak, just as having a function that never gets called is not a memory leak. After the program is loaded, nothing is ever allocated or de-allocated.

like image 65
Jonathon Reinhart Avatar answered Apr 12 '23 23:04

Jonathon Reinhart