Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are doing everything right in regard of passing an array of pointers and allocating memory. What leading to a heap corruption is incorrect usage of <code>strncpy</code> function. The arrays where you are trying to copy data to are slightly smaller than <code>MAXBUFF</code> in all cases. To fix this, you have to specify the size of destination array instead of <code>MAXBUFF</code>. For example, instead of:</p> <pre><code>strncpy(tmpPtr-&gt;fullName,inRecord,MAXBUFF); </code></pre> <p>... do (assuming that buffer is already filled with <code>\0</code> symbols):</p> <pre><code>strncpy(tmpPtr-&gt;fullName,inRecord, sizeof(tmpPtr-&gt;fullName) - 1); </code></pre> <p>Also, using <code>gets</code> function is not recommended as well as it could easily lead to buffer overruns. Try using <code>fgets</code> instead.</p> <p>Here is your modified example that works:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define MAXSTRUCTS 2 #define MAXBUFF 100 typedef struct { char fullName[41]; char address[41]; char cityState[41]; char zipcode[11]; } Persons; int readData(Persons *structPtrs[]); int main () { int totalStructs; int recs; Persons *structPtrs[MAXSTRUCTS]; totalStructs = 0; structPtrs[0] = NULL; totalStructs = readData(structPtrs); for(recs = 0; recs &lt; totalStructs; ++recs) { printf ("Record #%d - %s\n", recs + 1, structPtrs[recs]-&gt;fullName); } return 0; } int readData(Persons *strptr[]) { int tStructs = 0; int recs; char inRecord[MAXBUFF]; Persons *tmpPtr; tStructs = 0; for (recs=0; recs &lt; MAXSTRUCTS; ++recs) { memset (inRecord, 0, sizeof(inRecord)); if (fgets(inRecord, sizeof (inRecord) - 1, stdin)) { strptr[recs] = (Persons *)malloc(sizeof(Persons)); tmpPtr = strptr[recs]; memset (tmpPtr, 0, sizeof(Persons)); strncpy(tmpPtr-&gt;fullName,inRecord,sizeof(tmpPtr-&gt;fullName) - 1); fgets(inRecord, sizeof (inRecord) - 1, stdin); strncpy(tmpPtr-&gt;address,inRecord,sizeof(tmpPtr-&gt;address) - 1); fgets(inRecord, sizeof (inRecord) - 1, stdin); strncpy(tmpPtr-&gt;cityState,inRecord, sizeof(tmpPtr-&gt;cityState) - 1); fgets(inRecord, sizeof (inRecord) - 1, stdin); strncpy(tmpPtr-&gt;zipcode,inRecord, sizeof (tmpPtr-&gt;zipcode) - 1); strptr[recs] = tmpPtr; tStructs++; } else { if ( recs = 0 ) { exit (0); } recs=MAXSTRUCTS; } } return(tStructs); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload