Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strlen returning wrong value

I'm building a text editor using doubly linked lists. These are my structs:

#define N 4
typedef struct node
{
    char data[N];
    int size;
    struct node* next;
    struct node* prev;
}node;

typedef struct text
{
    struct node* head;
    struct node* tail;
    int count;
    int size;
}text;

This is the piece of code that I use to fill the first node.

void push_text (text * t, char * s)
{
    int i;
    int len = strlen(s);
    node *newnode, *nextnode, *head;

    newnode = create_node();
    t->count++;
    head = newnode;
    for (i=0; i<len; i++)
    {
        if (newnode->size < 4)
        {
            newnode->data[newnode->size] = s[i];
            newnode->size++;
        }
    .
    .
    .

When I print the node through printf or through the debugger the output is 4 chars long, as expected. Note that, I print it as soon as the first node is filled so the problem lies in this piece of code. However, when I use strlen(newnode->data) I get an output of 5. This is causing me many problems later on.

What's wrong here?

like image 305
user3484582 Avatar asked Apr 24 '26 21:04

user3484582


1 Answers

You are not copying the nul terminator, a c string needs a '\0' at the end, so if it has 4 characters it uses 5 bytes, the last one being '\0' which is not copied in your loop.

You should however use strcpy() instead of copying they bytes one by one in a loop.

The strlen() function scans the bytes until it finds the '\0', so the missing '\0' is causing the Wrong Value!, also that's a reason not to call strlen() in a loop, which is a very common mistake.

like image 111
Iharob Al Asimi Avatar answered Apr 26 '26 11:04

Iharob Al Asimi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!