Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

#include<stdio.h> #include<malloc.h> void main() { char *a = \"hey\"; free( a );

ID: 3871376 • Letter: #

Question

#include<stdio.h>
#include<malloc.h>
void main()
{
char *a = "hey";
free( a );
a = "hello";   
printf("%s",a);
}

_______________________________________

#include <stdio.h>

int main()
{
char* fileName;
printf("Specify file name you would like to print to: ");
scanf("%s",&fileName);

FILE* file1 = fopen(fileName, "a+");

char c;
while ((c=getchar()) != EOF)
{
fprintf(file1, &c);
}

fclose(file1);

printf("CTRL+d is a correct ending");

return 0;
}

_________________________________________________

please make these programs work with no errors or seg faults and explain in comments why you made the changes in the codes

Explanation / Answer

Hi
1.To answer this, you have to understand the need of using free(), this is used to free memory that we create on heap i.e by using malloc
ex: char a[10]="question" //this is created on stack and we should not use free on this
   char a*=malloc(10) // this is on heap and this we should free when we are done with it
hence you get error when you free a memory on heap
thats why we can modify the code to allocate memory from heap
#include<stdio.h>
#include<malloc.h>
void main()
{
char *a = "hey";
a=malloc(10);
free( a );
a = "hello";   
printf("%s",a);
}
Now, hello is printed without any error.
2. in this program, we are using fclose(file1) which could be dangerous when file1 is corrupted or null, hence we should always add a null check before doing that, once we add it, it runs fine

#include <stdio.h>

int main()
{
char* fileName;
printf("Specify file name you would like to print to: ");
scanf("%s",&fileName);

FILE* file1 = fopen(fileName, "a+");

char c;
while ((c=getchar()) != EOF)
{
fprintf(file1, &c);
}
if (file1 != NULL)
fclose(file1);

printf("CTRL+d is a correct ending");

return 0;
}


Thumbs up if this was helpful otherwise let me know in comments