int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
free(memory);
}
This will crash. You're setting the pointer to memory location 10 and then asking the system to release the memory. It's extremely unlikely that you previously allocated some memory that happeneds to start at 0x10, even in the crazy world of virutal address spaces. Furthermore, IF malloc failed, no memory has been allocated, so you do not need to free it.
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
}
free(memory);
This is also a bug. If malloc fails, then you are setting the pointer to 10 and freeing that memory. (as before.) If malloc succeeds, then you're immediately freeing the memory, which means it was pointless to allocate it! Now, I imagine this is just example code simplified to get the point across, and that this isn't present in your real program? :)