zzzbbx
zzzbbx

Reputation: 10161

c memory allocation

I have the following problem. The code is this

num_tokens++;
words = (char**) realloc(words, sizeof(char**) * (num_tokens + 1) );
words[num_tokens] = (char *) malloc(sizeof(char) * strlen(tmp)+1 );
strcpy(words[num_tokens], tmp);

where num_tokens is initially set to 0 and words contains, initially, one pointer to a string. I find that when num_tokens gets to one, and tmp is copied into words[1], words[0] changes as well. What might be the problem?

thanks

Upvotes: 0

Views: 252

Answers (3)

user458577
user458577

Reputation:

There seems a discrepancy between your counter and the meaning you assign to it. The num_tokens reflects the number of tokens you have in your words array. That means that in your allocation you should allocate 'num_tokens' and not 'num_tokens+1'.

Then, you should assign at num_tokens-1.

If you do not, you will as far as I see it never write into the 0 position, which might lead to unitialized data there, and your consequent feeling that the data 'changed' or got 'overwritten'

Summarized: words[0] will never be written to with this type of code and you will find random data there.

Upvotes: 2

Neigyl R. Noval
Neigyl R. Noval

Reputation: 6038

Place num_tokens++; after strcpy(); because at the strcpy line, num_tokens is already 1. num_tokens 0 is not defined. Thanks.

Upvotes: 0

Huang F. Lei
Huang F. Lei

Reputation: 1865

num_tokens++; // 0 => 1

strcpy(words[num_tokens], tmp); // copy tmp to words[1]

Upvotes: 0

Related Questions