#Weird changing of struct values

38 messages · Page 1 of 1 (latest)

hollow agate
#

So, I have seen this kind of behavior few times before but really have no clue about why that would happen

    JsonArrayT *array = JsonArray_new(strlen(expression) / 2);
    printf("%lu %lu\n", array->length, array->allocated);
    char *str = strdup(expression);
    char *token;
    printf("%lu %lu\n", array->length, array->allocated);

output:

0 4
140146654475791 4

why is the value of length changing??

shrewd parcelBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

true surge
#

whats the context

#

im assuming you did something wrong with the allocation

#

maybe made it a pointer to a local variable and its getting corrupted

#

idk

ivory violet
#

is this your actual code or a contrived example?

true surge
#

@hollow agate give more context

#

what does JsonArray_new do

hollow agate
#
JsonArrayT *
JsonArray_new(size_t size)
{
    JsonT *array = malloc(sizeof(JsonT) * size);
    return &(JsonArrayT){.array = &array, .length = 0, .allocated = size};
}
#

I think its because i didn't allocate memory for the return object

ivory violet
#

yeah, that's it

ivory violet
#

you're returning a pointer to the stack

#

but after the function exits, you no longer own that memory

true surge
#

yea

hollow agate
true surge
#

whenever you call a function it makes a new frame

#

this exists in one frame

#

then when you call strdup it overwrites the data with garbage

hollow agate
#

ah ok

#

thanks 👍

true surge
#

why not return JsonArrayT{ .array = array, .length = 0, .allocated = size }

#

i dont think it needs to be a pointer since the array already is

hollow agate
#

the array inside JsonArrayT is supposed to an array of pointers to JsonT

true surge
#

then youre not doing it right

#
JsonT **array = malloc(sizeof(JsonT*) * size);
#

you made a single pointer before

#

and then pointed to that

hollow agate
#

oh right

true surge
#

[[ json ]] what you had
[[ json ], [ json ], [ json ], ...] what you want

#

of course now you need to initialize the json pointers as well

#

id probably have it be an array of json objects

#

and each of those has a string or whatever in it as a data member

hollow agate
#

thats what i had before, decided to change it for some reason

#

anyways, thanks for advice 😄

#

!solved