Understanding Results With Valgrind
For the following code I have the following defintion:
typedef struct string {char* data; int length;} string;
If I run the following code with valgrind, I got conditional jump or move depends on unitinialized value and seg. fault:
string* s = (string*) malloc(sizeof(string));
strcpy("Hello", s->data);
free(s);
First of all, I can't understand why I got above errors.
I thought if I add to that code free(s->data)
it will freed memory but program will run ok.
How I think:
I know sizeof(string)
equal to 4(pointer to char) + 4(int) = 8.
then we allocate 8 bits for s.
strcpy will copy the string into data but I got a problem here. why?
Answer
There are multiple problems:
string* s = (string*) malloc(sizeof(string));
which should better be
string* s = malloc(sizeof(*s));
allocates memory for s->data
, but does not make s->data
point to any valid memory location. If you want to make use of the memory location, you need to make sure that it points to a valid memory location. For example: you'd need to malloc()
for s->data
seperately.
That said, the syntax for strcpy()
says, it's strcpy(dest, source)
, so in your case
strcpy("Hello", s->data);
attempts to
- read from an unitilized memory location
- write into a string literal
either of which invokes undefined behaviour.
You should write
strcpy(s->data, "Hello");
after ensuring s->data
is a valid destination.
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page