<p>I'm getting some strange, intermittent, data aborts (&lt; 5% of the time) in some of my code, when calling <code>memset()</code>.  The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act.</p>

<p>I'm using the following code:</p>

<pre><code>char *msg = (char*)malloc(sizeof(char)*2048);
char *temp = (char*)malloc(sizeof(char)*1024);
memset(msg, 0, 2048);
memset(temp, 0, 1024);
char *tempstr = (char*)malloc(sizeof(char)*128);

sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);
strcat(msg, temp);

//Add Data
memset(tempstr, '\0', 128);
wcstombs(tempstr, gdevID, wcslen(gdevID));
sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL);
strcat(msg, temp);
</code></pre>

<p>As you can see, I'm not trying to use memset with a size larger that what's originally allocated with <code>malloc()</code></p>

<p>Anyone see what might be wrong with this?</p>

[{'answer_id': 22464, 'author': 'Doug', 'author_id': 1618, 'author_profile': 'https://Stackoverflow.com/users/1618', 'pm_score': 0, 'selected': False, 'text': '<p>Have you tried using Valgrind? That is usually the fastest and easiest way to debug these sorts of errors. If you are reading or writing outside the bounds of allocated memory, it will flag it for you.</p>\n'}, {'answer_id': 22473, 'author': 'Joel Spolsky', 'author_id': 4, 'author_profile': 'https://Stackoverflow.com/users/4', 'pm_score': 5, 'selected': True, 'text': "<p><code>malloc</code> can return <code>NULL</code> if no memory is available. You're not checking for that.</p>\n"}, {'answer_id': 22486, 'author': 'FreeMemory', 'author_id': 2132, 'author_profile': 'https://Stackoverflow.com/users/2132', 'pm_score': 2, 'selected': False, 'text': "<p>There's a couple of things. You're using <code>sprintf</code> which is inherently unsafe; unless you're 100% positive that you're not going to exceed the size of the buffer, you should almost <em>always</em> prefer <code>snprintf</code>. The same applies to <code>strcat</code>; prefer the safer alternative <code>strncat</code>.</p>\n\n<p>Obviously this may not fix anything, but it goes a <em>long</em> way in helping spot what might otherwise be very annoying to spot bugs.</p>\n"}, {'answer_id': 22488, 'author': 'Adam Haile', 'author_id': 194, 'author_profile': 'https://Stackoverflow.com/users/194', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>malloc can return NULL if no memory is\n  available. You\'re not checking for\n  that.</p>\n</blockquote>\n\n<p>Right you are... I didn\'t think about that as I was monitoring the memory and it there was enough free.  Is there any way for there to be available memory on the system but for malloc to fail?</p>\n\n<blockquote>\n  <p>Yes, if memory is fragmented. Also, when you say "monitoring memory," there may be something on the system which occasionally consumes a lot of memory and then releases it before you notice. If your call to <code>malloc</code> occurs then, there won\'t be any memory available. -- <strong>Joel</strong></p>\n</blockquote>\n\n<p>Either way...I will add that check :)</p>\n'}, {'answer_id': 22495, 'author': 'Adam Haile', 'author_id': 194, 'author_profile': 'https://Stackoverflow.com/users/194', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>You're using sprintf which is\n  inherently unsafe; unless you're 100%\n  positive that you're not going to\n  exceed the size of the buffer, you\n  should almost always prefer snprintf.\n  The same applies to strcat; prefer the\n  safer alternative strncat.</p>\n</blockquote>\n\n<p>Yeah..... I mostly do .NET lately and old habits die hard.  I likely pulled that code out of something else that was written before my time...</p>\n\n<p>But I'll try not to use those in the future ;)</p>\n"}, {'answer_id': 22496, 'author': 'TK.', 'author_id': 1816, 'author_profile': 'https://Stackoverflow.com/users/1816', 'pm_score': 0, 'selected': False, 'text': '<p>You know it might not even be your code... Are there any other programs running that could have a memory leak?</p>\n'}, {'answer_id': 22799, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 1, 'selected': False, 'text': '<p><code>wcstombs</code> doesn\'t get the size of the destination, so it can, in theory, buffer overflow.</p>\n\n<p>And why are you using <code>sprintf</code> with what I assume are constants? Just use:</p>\n\n<p><code>EZMPPOST" " EZMPTAG "/" EZMPVER " " TYPETXT EOL</code></p>\n\n<p>C and C++ combines string literal declarations into a single string.</p>\n'}, {'answer_id': 107412, 'author': 'davenpcj', 'author_id': 4777, 'author_profile': 'https://Stackoverflow.com/users/4777', 'pm_score': 0, 'selected': False, 'text': "<p>It could be  your processor. Some CPUs can't address single bytes, and require you to work in words or chunk sizes, or have instructions that can only be used on word or chunk aligned data. </p>\n\n<p>Usually the compiler is made aware of these and works around them, but sometimes you can malloc a region as bytes, and then try to address it as a structure or wider-than-a-byte field, and the compiler won't catch it, but the processor will throw a data exception later. </p>\n\n<p>It wouldn't happen unless you're using an unusual CPU. ARM9 will do that, for example, but i686 won't. I see it's tagged windows mobile, so maybe you do have this CPU issue.</p>\n"}, {'answer_id': 107431, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 0, 'selected': False, 'text': '<p>Instead of doing <code>malloc</code> followed by <code>memset</code>, you should be using <code>calloc</code> which will clear the newly allocated memory for you. Other than that, do what Joel said.</p>\n'}, {'answer_id': 128706, 'author': 'Airsource Ltd', 'author_id': 18017, 'author_profile': 'https://Stackoverflow.com/users/18017', 'pm_score': 0, 'selected': False, 'text': '<p>NB borrowed some comments from other answers and integrated into a whole. The code is all mine...</p>\n\n<ul>\n<li>Check your error codes. E.g. malloc can return NULL if no memory is available. This could be causing your data abort.</li>\n<li>sizeof(char) is 1 by definition</li>\n<li>Use snprintf not sprintf to avoid buffer overruns \n\n<ul>\n<li>If EZMPPOST etc are constants, then you don\'t need a format string, you can just combined several string literals as STRING1 " " STRING2 " " STRING3 and strcat the whole lot. </li>\n</ul></li>\n<li>You are using much more memory than you need to.</li>\n<li>With one minor change, you don\'t need to call memset in the first place. Nothing\nreally requires zero initialisation here.</li>\n</ul>\n\n<p>This code does the same thing, safely, runs faster, and uses less memory.</p>\n\n<pre><code>    // sizeof(char) is 1 by definition. This memory does not require zero\n    // initialisation. If it did, I\'d use calloc.\n    const int max_msg = 2048;\n    char *msg     = (char*)malloc(max_msg);\n    if(!msg)\n    {\n       // Allocaton failure\n       return;\n    }\n    // Use snprintf instead of sprintf to avoid buffer overruns\n    // we write directly to msg, instead of using a temporary buffer and then calling\n    // strcat. This saves CPU time, saves the temporary buffer, and removes the need\n    // to zero initialise msg.\n    snprintf(msg, max_msg, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);\n\n   //Add Data\n   size_t len = wcslen(gdevID);\n   // No need to zero init this\n   char* temp = (char*)malloc(len);\n   if(!temp)\n   {\n      free(msg);\n      return;\n   }\n   wcstombs(temp, gdevID, len);\n   // No need to use a temporary buffer - just append directly to the msg, protecting \n   // against buffer overruns.\n   snprintf(msg + strlen(msg), \n           max_msg - strlen(msg), "%s: %s%s", "DeviceID", temp, EOL);\n   free(temp);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/22459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194/']