Matt
Matt

Reputation: 1901

c string allocation differences?

I have a functions which takes a char * as its only argument. I then perform some strtok operations on it. Sometimes it works and sometimes it doesent. It working depends upon how the string was constructed. For instance here are the two cases.

int main()
{
   char glob[] = "/abc/def/ghi";
   char *glob2 = "/abc/def/ghi";

   func(glob);  //this one works
   func(glob2); //this one doesnt work

   return 0;
}

What is the difference between the two allocation methods and why does strtok blow up on the second one?

Upvotes: 3

Views: 1734

Answers (4)

James Youngman
James Youngman

Reputation: 182

The other comments are correct; you should use strtok_r() instead.

Upvotes: -1

aJ.
aJ.

Reputation: 35470

strtok() basically modifies the input string.

char *glob2 = "/abc/def/ghi";

In above case the glob2 points to read-only data and hence it fails, whereas with 'char glob[] = "/abc/def/ghi";' the data is not read-only, it's available in char array. Hence it allows the modifications.

Upvotes: 12

sepp2k
sepp2k

Reputation: 370415

char[] str1 = "foo" allocates an array of the chars on the stack (assuming this is inside a function). That array can be modified without a problem.

const char *str = "foo" gives you a pointer to the string foo, which will usually reside in read-only memory.

char *str = "foo" will do the same thing but implicitly remove the const (without actually changing the fact that the pointer likely points to read-only memory).

Upvotes: 7

kmarsh
kmarsh

Reputation: 1398

Strtok writes to the memory allocated to the string.

You cannot write to statically allocated string memory on most compilers/runtimes/hardware. You can write to the stack.

Upvotes: 6

Related Questions