Thanks for comments laserlight and matsp. NULL and (char*) cast are deleted now.
I've been working away on this and it has evolved a little more. I have a sense that I've made a mistake here, but it is closer to the direction I want to go in.
I have a struct, and an initialisation function "void wordNew". My uncertainty is over whether I should free the temporary pointer (last 2 lines of the function).
In the function I copy the address to the struct's char pointer. My sense from what I have read is that I should ("free what you malloc"), but I am concerned that by freeing the memory , it will get overwritten.
main.c
Code:
int main (int argc, const char * argv[]) {
Word w;
wordNew(&w, "Hello");
return 0;
}
word.h
Code:
typedef struct {
char *word;
int length;
int isAllocated;
}Word;
void wordNew(Word *wordStruct, const char * newWord);
word.c
Code:
void wordNew(Word *wordStruct, const char * newWord) {
int isAllocated;
char* word;
int length;
length = strlen(newWord) +1;
word = malloc(length); //sizeof(char) = 1 byte
if (word != NULL) {
isAllocated = 1;
strlcpy(word, newWord, length); //strlcpy adds '\0'
wordStruct->word = word;
wordStruct->length = length;
wordStruct->isAllocated = isAllocated;
}
else {
isAllocated = 0;
}
Are either of these necessary??
free(word); //
word = NULL; //is this over-cautious???
}