kaljak
kaljak

Reputation: 1273

Char* is behaving weird (changing value in progress)

Variables:

struct configSetting {
    char *value;
};
char *stringResult;
char str[255];
int intResult;
int *p_intResult;
int i = 0;
p_intResult = &intResult;

I am converting an int into a string:

struct configSetting settings[NUMBEROFSETTINGS];
settings[i].value = itoa(intResult, str, 10);

printf prints the correct value into the console:

printf("\nVALUE: %s", settings[i].value);

After that I am writing the value in another function into the console, the output changes between those two printf:

printf("\nTEST 1: %s;%i", settings[15].value, strlen(settings[15].value));
printf("\nTEST 2: %s;%i", settings[15].value, strlen(settings[15].value));

That's the result in the console: TEST 1: 50;2 TEST 2: ý³↑;3

So the char* in settings[15].value is changing between the printf's and I have no idea why?

Thanks in advance!

Upvotes: 1

Views: 142

Answers (2)

WhozCraig
WhozCraig

Reputation: 66194

You're overwriting the last value of your itoa() with the subsequent invoke.

This call:

settings[i].value = itoa(intResult, str, 10);

is using the variable str[]. Each time you do this you overwrite the last results. Further, if str[] is local and settings is global, the resulting pointers stored are no longer valid, and it is undefined behavior.

Either dynamically allocate the value string with malloc() or strdup() or some such, or change this:

struct configSetting {
    char *value;
};

To include a real buffer, like this:

struct configSetting {
    char value[64];
};

And then just itoa() directly to the setting:

itoa(intResult, settings[i].value, 10);

Upvotes: 4

Sergej Christoforov
Sergej Christoforov

Reputation: 1606

You are using the same str buffer and store a reference to it (settings[i].value = itoa(intResult, str, 10);) for every value converted. Next call to itoa will overwrite old value.

Upvotes: 2

Related Questions