Strings in gtk+ (c)
Hello!
I'm currently having a trouble with strings and allocation of memory ( i think ). float effect = calc_power_r(); //calc_power is my own function. char StartText[] = "Effekt: "; char* effectString = (char *)malloc(sizeof(float)); char* effectLabel = (char *)malloc(sizeof(effectString)+sizeof(StartText)); snprintf(effectLabel, strlen(effectString), "%f", effect); g_stpcpy(effectLabel, StartText); strcat(effectLabel, effectString); gtk_label_set_text(GTK_LABEL(test->EffectResultLabel),effectLabel); free(effectLabel); free(effectString); I've noticed if i change the allocation of effectString to a static string like char effectString[50]; and snprintf(effectLabel, 50, "%f", effect); it works like a charm. So i suppose I'm doing something wrong with the allocation of the string or this line. snprintf(effectLabel, strlen(effectString), "%f", effect); //Best Regards, Linusovic |
I think it is because of the effectString allocation too. effectString is a string made of chars so instead of sizeof(float) which would just return the size of the float datatype you need to allocate enough memory for the number of characters that will be used when the float is converted to a string.
Something like this would allocate enough memory for a 50 char string, similar to what you did with "char effectString[50];" Code:
char* effectString = (char *)malloc(50 * sizeof(char)); |
I think af7567 hit it. That's the first thing I noticed too.
If you want to store a string representation of a float, you don't do something like: Code:
Code:
#include <stdio.h> Code:
$ ./floattest |
All times are GMT -5. The time now is 06:21 AM. |