Facebook interview: Implement readline function [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
The question is
Implement a function char* readLine(); which returns single lines from
a buffer. To read the buffer, you can makes use of a function int
read(char* buf, int len) which fills buf with upto len chars and
returns the actual number of chars filled in. Function readLine can be
called as many times as desired. If there is no valid data or newline
terminated string available, it must block. In order to block, it can
use read function which in turn will block when it doesn't have
anything to fill the buf.
I don't know how to proceed and what kind of approach is expected.
I could not understand what the interviewer expects here. I just need direction to move ahead and not the exact function.

Allocate an appropriately sized buffers.
If you don't have characters in your read buffer, read in a new chunk.
If the next character from the read buffer is a newline, return the result buffer.
If the result buffer is full, bug out and whine about lines being too long.
Otherwise, add the next character from the read buffer into the result buffer.
NOTE: The answer to the question as asked is a security issue waiting to happen, and also a potential memory leak.

Related

After I use malloc, program suddenly asks for input [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm a newbie programmer
//allocating space for final output
//text_count is given by another function, let's just say i have a value for it
//out is my typedef struct
out *fin[text_count];
for(i=0; i<text_count; i++){
fin[i] = malloc(sizeof(out));
}
//this is a test
fin[1]->appearances = 1;
printf("%d",fin[1]->appearances);
// ..other code
I noticed that after this allocation, program suddenly outputs this:
1_
The underscore is blinking, indicating it needs an input.
What can be my problem here? Is it the allocation? Or the codes down below?
okay sorry, let me clarify this, im using codeblocks . so when i get a blinking cursor it means it needs an input. and after i got this output, an infinite loop of inputs seems to be happening.
You're simply seeing the text terminal's cursor. It may be blinking or it may not, that doesn't mean anything in itself.
You might want to add a linefeed:
printf("%d\n", fi[1]->appearances);
to get the output on a line of its own.
A cursor after your printf does not mean, that it is waiting for input.
You can confirm this, by using strace, if it is waiting at read syscall.
Usage:
strace ./myApplication arg1 arg2...

printf to prevent segmentation fault in c [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
The following is a part of a function.
l->length[l->cl] = atoi(p->wds[p->cw]);
printf("FD %d\n", l->length[l->cl]);
p->cw = p->cw + 1;
l->cl = l->cl + 1;
printf("prevent from seg fault\n");
instr(p);
If I remove the printf("prevent from seg fault\n"); I get segmentation fault, but if I keep it it runs and go to the nest function and so on.
So my question is just in general why does this happen, I know I am not showing enough of my code so you can see why the segmentation happen, but if there is any general explanation for this, I also had this in another place in my program but at the end I could remove it?
Regards Orri
As far as the standard is concerned any changes made to a program that invokes undefined behaviour can have any result - there doesn't have to be a logic behind it. And in fact it is very seldom fruitful to try to reason about how a given implementation behaves when encountering undefined behaviour.
That said if a call to printf (or any other function) changes the behaviour of your program (beyond the obvious change of printing what it's supposed to, of course), one possible explanation is that you have an invalid pointer somewhere that points to a local variable that's out of scope. If that variable previously lived in the stack memory that's now used by printf for its own local variables, that means the memory that the pointer points to will now be overridden with a new value. And that can of course change the behaviour of any code that use the pointer.

How to accept input with ints and strings with spaces? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to accept input from a file. This file is in the format of an integer, followed by a tab, followed by a string (which may or may not have spaces).
for example:
1\tls -l
2\tls
I tried using:
int cmd_num;
char command[80];
while (fscanf(ifp, "%d\t%s", &cmd_num, command) != EOF) {
...
}
However, this failed when it saw a space. Any help?
You probably need to use a scan-set to read the string:
if (fscanf(fp, "%d\t%79[^\n]\n", &cmd_num, command) != 2)
...error handling...
else
...use cmd_num and command...
Note the size constraint in the format string to prevent buffer overflow.
Note, too, that you will not know whether the newline is matched. You might be better off using fgets() to read the whole line (or getline()), and then using sscanf() instead of fscanf(); at least you'll know whether the newline was collected (and can gobble to the newline if necessary).
Try this in your fscanf function:
fscanf(fp,"%d\t%[^\n]s",&cmd_num,command);
This will surely work...

Why does char * malloc give me a seg fault with scanf? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
char * input = (char*)malloc(256);
scanf("%s", input);
Seg fault. Why? I have a lot of trouble with strings in C, but I feel like everything is done right here. I even followed an example from a 100k+ SO user to the letter.
The bug could be caused by:
malloc() failing to allocate any memory, check the result against NULL.
by a buffer overrun from scanf, more than 256 characters.
by forgetting to include <stdlib.h> and then typecasting the result of malloc. More info here.
You need to ensure your buffer is large enough, including enough space for the trailing NUL (0 byte) at the end of the string. Otherwise, you get a buffer overflow that may lead to a segfault.

Reverse the place of the string in C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I want reverse the string in particular format.
For example, "My name is Nishant" should be converted to "Nishant is name My".
If you have your words in a char[] words array then it is a simple loop:
for (i = 0; i < mid; i++)
exchange(words[i], words[number_of_words - i]);
for sane definitions of mid, number_of_words and exchange.
If all you have is a big char containing the entire statement, doing a strtok first is helpful. Then, use the above loop.
Give our regards to your instructor. If this is a homework assignment, you should write the code yourself.
Here is a little hint, though: use a char pointer to iterate through each character in the array until you hit the NUL terminator at the end. Now iterate in reverse until you hit a space. Save your place in another pointer, move forward by one then copy each of the characters up to but not including the NUL into your output buffer.
Now retrieve the position of that last space in that other pointer where you saved your place, and back up again. When you move forward, you actually need to stop when you encounter either a space of a NULL - ASCII '\0' or a zero byte - and not just a NUL.
It would be a little faster if you save the positions of each of the spaces in some kind of list as you iterate forward at the beginning. That way you don't then need to iterate backward over the entire string, with short iterations over each word. The code would be a little more complicated.
The increased efficiency would be insignificant for short strings like individual English sentences, but would be quite a lot of you were reversing a large file that you just read into memory.

Resources