I have the following code that has been working for the last couple of months, but have recently started to crash on occasion (when running in a multi-threaded application):
struct some_struct {
char* m_str1;
char* m_str2;
}
struct some_struct*
set_some_struct(const char* p_str1, const char* p_str2) {
struct some_struct* some_struct_ptr =
(struct some_struct*)malloc(sizeof(struct some_struct));
if (some_struct_ptr == NULL)
printf("malloc failed!\n");
size_t str1_len = strlen(p_str1) + 1;
size_t str2_len = strlen(p_str2) + 1;
some_struct_ptr->m_str1 = malloc(str1_len);
if (some_struct_ptr->m_str1 == NULL)
printf("malloc failed!\n");
some_struct_ptr->m_str2 = malloc(str2_len); // Crashes here
if (some_struct_ptr->m_str2 == NULL)
printf("malloc failed!\n");
strcpy(some_struct_ptr->m_str1, p_str1);
strcpy(some_struct_ptr->m_str2, p_str2);
return some_struct_ptr;
}
Running it gives me "The instruction at "0x7c81bb52" referenced memory at "0x00000002". The memory could not be "read"."
Is there anything obviously wrong with the code above that could have it misbehave under certain circumstances? If I run the function alone in a test program it works just fine, but it always crashes when running in the full application. Everything leading up to the third malloc seems just fine.
EDIT: Further investigation leads me to believe that it is earlier calls to malloc
that mess this one up. Is such a thing even possible? If I uncomment a function call being made previous to set_some_struct
and that involve several mallocs
then set_some_struct
will run just fine.