Effect of filling memory allocated by malloc()

cmalloc

Although I was able to correct my program and make it run properly, the reason why it wasn't working left me really curious.

I made a string with malloc and initialized it…then I did several strcat with it…and then I declares a file pointer…after that and if my string had more than approx. 26 chars the rest would be garbage…but if i declared the pointer previously to the string malloc it worked great. I just can't understand why, here it is some of the code if anyone thinks it's better to see more pls say so:

code:

char* holder=(char*)malloc(sizeof(char)*100);

for(i=0;i<100;i++)
    *(holder+i)='\0';

strcat(holder,"set xtics (");

//will ignore until the last n lines
for(i=0;i<26-n;i++)
    readline(sfd,line,29);

//will manage the last lines
char n_column[2];
char freq[3]={0};

for(i;i<26;i++)
{
    readline(sfd,line,29);
    sscanf(line+4,"%s",freq);
    write(out,freq,strlen(freq));
    write(out,"\n",1);
    strcat(holder,"'");
    sscanf(line,"%s",temp);
    strcat(holder,temp);        
    strcat(holder,"'");
    sprintf(n_column,"%d",counter); 
    strcat(holder," ");
    strcat(holder,n_column);
    //for the las one which won't have the ,
    if(i==25)
        strcat(holder,")");
    else
        strcat(holder,", ");
    counter++;      

}

//sending to gnuplot using pipe
printf("Before: %s\n",holder);
FILE *pipe = popen("gnuplot -persist","w"); //why can't it be here!!!!
printf("After: %s\n",holder);

output:

Before: set xtics ('a' 0, 'b' 1, 'c' 2, 'd' 3, 'e' 4, 'f' 5, 'g' 6, 'j' 7, 'k' 8, 'l' 9, 'm' 10, 'n' 11, 'o' 12, 'p' 13, 'q' 14, 'r' 15, 'u' 16, 'v' 17, 'w' 18, 'x' 19, 'y' 20, 'z' 21, 'h' 22, 'i' 23, 't' 24, 's' 25)

After: set xtics ('a' 0, 'b' 1, 'c' 2, 'd' 3, 'e' 4, 'f' 5, 'g' 6, 'j' 7, 'k' 8, 'l' 9, 'm' 10, 'n' 11, 'o'�

But if I change to:

FILE *pipe = popen("gnuplot -persist","w");

char* holder=(char*)malloc(sizeof(char)*100);
for(i=0;i<100;i++)
    *(holder+i)='\0';

Output is fine.

So why declaring the file pointer made such a difference? Or is something besides that?

Many thanks for you patience.

Best Answer

You have a 100 byte buffer and 208 byte string in it. The memory outside those 100 bytes does not belong to you.

Related Topic