Return Last 50 posts First 100 posts
I'm allocating memory twice.
1 Name: Anonymous : 2017-03-01 23:13
For some reason I'm allocating memory twice, but I'm not sure why. Can anyone see it?
I'm inserting a node at the end of a linked list. Here's the function:
/*
* inserts the address addr as a new listNode at the end of
* the list
*/
void insertBack(struct listNode *pNode, const char *addr){
struct listNode *tempNode;
//Check if next node is NULL; means we are at the end of the list
if(pNode->next == NULL)
{
//Create new node
struct listNode *newNode;
newNode = (struct listNode *)malloc(sizeof(struct listNode));
//Check if done properly
if(newNode == NULL)
{
printf("\nFailed to Allocate Memory.");
exit(-1);
}
//Initialize newNode->addr
strncpy(newNode->addr, addr, MAX_ADDR_LENGTH);
//Insert newNode
pNode->next = newNode;
newNode->next = NULL;
return;
}
else
{
//else set tempNode to the next node and try again
tempNode = pNode->next;
insertBack(tempNode, addr);
}
}
2 Name: Anonymous : 2017-03-06 06:15
In the C Programming Language, the strncpy function copies the first n characters of the array pointed to by s2 into the array pointed to by s1. It returns a pointer to the destination.
har * strncpy ( char * destination, const char * source, size_t num );
Copy characters from string
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
3 Name: Anonymous : 2017-03-06 06:25
shouldn't you just let malloc take care of the address
4 Name: Anonymous : 2017-03-06 11:00
That's the most bloated linked-list insert I've seen. If you really want to insert at the end and don't want to keep an end pointer for constant-time inserts (idiot), you don't need more than this:
while(pNode->next) pNode = pNode->next;
pNode->next = malloc(...);
...
5 Name: Anonymous : 2017-03-07 03:45
Probably should just insert at the front of the list, reversing a list would be easy enough
Return Last 50 posts First 100 posts