开发者

why here realloc modify original content?

What I am doing is simple:realloc the message buffer to one size(size_t)larger:size+1,but my original content is modified(how does '33' come out?):

message:0x9ead008
  0:0 0 0 0 0 0 0 0 0 0 
message:0x9ead008
  0:0 0 0 33 0 0 0 0 0 0 0 

my code is so simple that I found no where bugs could hide:

#include <stdlib.h>   
#include <string.h>

void print_message(int* message,long n)   
{   
    int i;    
    for(i=0;i<n;i++)   
    {   
        if(i%48==0)    
            printf("\n%3d:",i/48);   
        printf("%d ",message[i]);                
    }    
    printf("\n");        

}

void realloc_test()
{
    int n=10;

    int* message=(int*)malloc(n*sizeof(int));
    printf("message:%p\n",message);

    print_message(message,n);
    memset(message,0,n);
    message=(int*)realloc(message,n+1);
    printf("message:%p\n",message);
    print_message(message,n+1);

    free(message开发者_Go百科);    
}

int main(int argc,char* argv[])   
{   
    realloc_test();     
    return 0;   
}


There is an error in your program. In function realloc_test() change the line

message=(int*)realloc(message,n+1);

to

message=(int*)realloc(message,(n+1)*sizeof(int));

I think this will solve your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜