So me and my TA have been trying to figure out why this isnt working because for my assignment we have to use sprintf() and a whole new buffer to print out each line in a text file. without the sprintf() and printing it normally it works completely fine.
And this is what i got using sprintf()

Heres my code:
int buff = 1000;
char *ptr = mmap (NULL,buff, PROT_WRITE | PROT_READ ,MAP_PRIVATE| MAP_ANONYMOUS,0,0);
if(ptr == MAP_FAILED){
printf("Mapping Failed\n");
return 1;
}
char *oof = mmap (NULL,buff, PROT_WRITE | PROT_READ ,MAP_SHARED| MAP_ANONYMOUS,0,0);
if(oof == MAP_FAILED){
printf("Mapping Failed\n");
return 1;
}
int f1 = open("file2.txt", O_RDWR);
int fd = open("file.txt", O_RDONLY);
if(fd < 0){
printf("Uh oh u made an oopsie\n");
}else{
printf("Hey look at that it opened\n\n");
}
int length = read(fd,ptr,sizeof(char)*buff);
int count = 1;
for(int i = 0; i<length;i++){
if(ptr[i] == '\n'){
count++;
}
}
int lengths[count];
for(int i = 0;i<count;i++){
lengths[i] = 0;
}
int m = 0;
for(int i = 0;i<length;i++){
lengths[m]++;
if(ptr[i] == '\n'){
m++;
}
}
int j = 0;
int k = 0;
char **lineArray = (char **) malloc(sizeof(char *) *count);
for(int i = 0; i<count; i++){
lineArray[i] = (char *) malloc(sizeof(char)* lengths[i]);
k = 0;
while(ptr[j] != '\n')
{
lineArray[i][k] = ptr[j];
j++;
k++;
}
j++;
sprintf(oof,"\nlineArray[%d] = %s\n",i,lineArray[i]);
write(1,oof,sizeof(char)*buff);
//printf("\nlineArray[%d] = %s\n",i ,lineArray[i]);
}
I have messed around with this so much and i know its something to do with the mmap buffer stuff but i cant figure out what to do to fix it.

In this part:
you are unconditionally writing
buff(=1000) bytes, so it may contain data in previous lines.You should get the length of string from the return value of
sprintfand use that as the size to write:Also you have to add
'\0'to terminate the string, orsprintfwith%swill go reading beyond the end of the buffer and invoke undefined behavior.