BigBug
BigBug

Reputation: 6290

Length of size_t not correct?

theMessageMaxLength keeps giving me a value of 4 even if the length is larger than 4. Why is this happening and how do I fix it? It is of type size_t and I don't have it declared anywhere, rather it is just a value being passed in as such:

place_value(int task, struct PDB *llist, char *theMessage, size_t theMessageMaxLength)

The above method is being called as follows:

place_value(task, llist, theMessage, sizeof(theMessage)); 

I'm assuming this is where the length gets set to 4, however, shouldn't it be set to something larger if my message is larger? How would I increase the size so it's not just 4...?

and then used like this within the function it is being passed into:

strncpy(llist->data1, theMessage, theMessageMaxLength);
llist->data1[theMessageMaxLength] = '\0';

Upvotes: 1

Views: 134

Answers (3)

shinkou
shinkou

Reputation: 5154

sizeof(theMessage) is literally same as sizeof(char *). Perhaps you were confused with the situation below:

char theMessage[1024];

/* ... some code here ...*/

printf("sizeof(theMessage): %zd\n", sizeof(theMessage));

If you allocate memory for theMessage, then you should provide its size.

EDIT: As a side node, you may be interested in strndup which allocates memory automatically and appends a NULL character at the end to the destination string. But of course, you'll have to be careful and don't forget to free it.

Upvotes: 1

edwardw
edwardw

Reputation: 13972

You are measuring the size of a pointer, which is 4 (on 32-bit platform).

Upvotes: 0

Mysticial
Mysticial

Reputation: 471279

It looks like you're confusing sizeof() with strlen().

sizeof(theMessage) will only give you the size of a char* which is a pointer - (4 bytes in your case). If you want the length of the string, you'll need to use strlen(theMessage) instead.

place_value(task, llist, theMessage, strlen(theMessage)); 

Upvotes: 8

Related Questions