If you're trying to make a string type I find the approach you've taken a little weird.
You should find newlines with strchr and place a zero there, using the pointer that it returns.
I also find it a bit safer to just make a deep copy of the string upon creation rather than a simple pointer assignment. That way, the body of the string variable will always be available until you destroy the string, and isn't dependent on some other pointer. It would be quite a surprise if the other pointer freed the body of your string variable earlier than you wanted.
Also, what if you make a string variable from a literal like "hello world"? A copy would be necessary then also.
If I were doing this, here is what it would look like, since I'm bored. This compiles:
Code:
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct strings_t
{
char * body;
size_t length;
};
struct strings_t makeString (const char * cs)
{
struct strings_t str = {NULL, 0};
if (cs == NULL)
return str;
str.length = strlen(cs);
str.body = malloc(str.length + 1);
str.body = (str.body == NULL) ? NULL : strcpy(str.body, cs);
return str;
}
struct strings_t readLine (size_t linesize, FILE * stream)
{
struct strings_t buf = {NULL, 0};
char * line = malloc(linesize + 1);
if (line == NULL)
return buf;
if (fgets(line, linesize, stream) != NULL) {
char * nl = strchr(line, '\n');
if (nl != NULL)
*nl = '\0';
buf = makeString(line);
}
free(line); /** buf.body is a separate copy **/
return buf;
}
void destroyString (struct strings_t old)
{
free(old.body);
}