We have a cortex M4F controller, using Keil uVision5 to compile and J-Link base to debug our applications. In our application we have a uint8 type global buffer of some x size, our issue is when we do memset for this global buffer controller is going to hardfault handler, we found the problem is with memory alignment for the global buffer and the problem is fixed by adding __attribute__((aligned)) to the global buffer
uint8_t global_buf[GLOBAL_BUFF_LEN] __attribute__((aligned));
Can someone suggest any compiler options which would fix this issue without adding something to my code (we don't want to align all the the buffers in use).
uint8_t global_buf[GLOBAL_BUFF_LEN]; //when I call memest from some function memset(global_buffer, 0, buf_length);
You've shown a definition of global_buf, but your memset call is actually using global_buffer.
So what you've shown is not the actual code that causes the problem!
Also, how is buf_length set?
Please post the minimum complete example which demonstrated the problem.
Never manually re-type code into a post - always use copy & paste.
The M4F has a few instructions that will fault due to memory alignment, these are typically 64-bit load and store instructions (LDRD,STRD), frequently encounter with double variables, or cases where the compiler thinks it can fold a pair of 32-bit accesses.
You should look at the processor instructions that are faulting, the registers in those cases, and what your source code was doing.
When processing unaligned data you might want to memcpy() to an aligned structure and process it from there. This might be needed with data streaming from a device where the protocol only has byte level alignment of its data, or file data which is packed to save space rather than be efficient to access by the CPU.
Cure the problem, don't meddle with the symptoms.
I guess (think) the OP's assumption is incorrect.
If I define a uint8_t buffer, compiler knows it is not aligned, and would not do anything that need the buffer to be aligned.
I tend to agree.
"If I define a uint8_t buffer, compiler knows it is not aligned, and would not do anything that need the buffer to be aligned."
Indeed.
Hence the earlier suggestion that (s)he needs to look further into why, exactly, (s)he was getting the Hard Fault...
Also, the fact that the code posted is not the full story suggests that there is probably something else going on - maybe casting something that needs alignment onto the unaligned buffer ... ?