Guest User

Untitled

a guest
Aug 21st, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. Segmentation fault when initialization array
  2. typedef struct {
  3. char *s;
  4. int len;
  5. } string_t;
  6.  
  7.  
  8. typedef struct {
  9. uint32_t numb;
  10. } msg_t;
  11.  
  12. void myfunct()
  13. {
  14. msg_t msg;
  15. memset(&msg, 0, sizeof(msg));
  16. msg.numb = 1;
  17. char *ClientSendBuf[sizeof(msg)];
  18. string_t buffer = {ClientSendBuf[sizeof(msg)],strlen(ClientSendBuf[sizeof(msg)])};
  19. }
  20.  
  21. void myfunct()
  22. {
  23. msg_t msg;
  24. memset(&msg, 0, sizeof(msg));
  25. msg.numb = 1;
  26. char ClientSendBuf[] = "This is my message";
  27.  
  28. string_t buffer = {
  29. strdup(ClientSendBuf), /*Can return NULL so add error check*/
  30. strlen(ClientSendBuf)
  31. };
  32. /** Or **/
  33. string_t buffer;
  34. buffer.s = malloc(strlen(ClientSendBuf)+1);
  35. if(NULL == buffer.s)
  36. {
  37. /* Memory allocation failed. Handle error.*/
  38. }
  39. /* Zero fill */
  40. memset(buffer.s, 0, strlen(ClientSendBuf)+1);
  41. strcpy(buffer.s, ClientSendBuf);
  42. buffer.len = strlen(ClientSendBuf);
  43. /*Opeartions with buffer*/
  44. /*Call free in both cases !*/
  45. free(buffer.s);
  46. }
  47.  
  48. char *ClientSendBuff[sizeof(msg)];
  49. string_t buffer[sizeof(msg)];
  50. int i;
  51.  
  52. for(i = 0; i < sizeof(msg); i++) {
  53. ClientSendBuff[i] = malloc(100); // you have to initialize (and free when
  54. buffer[i].s = ClientSendBuff[i]; // you don't need them anymore) every pointer
  55. buffer[i].len = 100;
  56. }
Add Comment
Please, Sign In to add comment