我在运行使用此函数的程序时遇到一些问题
static
int upload_build_buffer(char **upload_buffer,int seq_n, char* buffer) {
char *up_buffer = NULL;
assert(buffer);
assert(upload_buffer);
*upload_buffer = NULL;
*upload_buffer = malloc((SIZE_SEQ_N+strlen(buffer)+1) * sizeof(char));
if(!(*upload_buffer))
return 1;
up_buffer = malloc((SIZE_SEQ_N+strlen(buffer)+1) * sizeof(char));
if(!(up_buffer))
return 1;
/* prints formatted sequence number in its string */
snprintf((*upload_buffer), SIZE_SEQ_N+1, "%5d", seq_n);
(*upload_buffer)[SIZE_SEQ_N] = 0;
/* creates payload -> buffer = seq_number + buffer */
strncpy(up_buffer,strncat((*upload_buffer), buffer, SIZE_PAYLOAD), SIZE_SEQ_N + SIZE_PAYLOAD);
free(*upload_buffer);
*upload_buffer = up_buffer;
return 0;
}
在运行时,如果我多次执行此函数,就会出现此错误:
malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
函数的调用如下:
/* builds buffer to send */
if(seq_numbered_buffer) {
free(seq_numbered_buffer);
seq_numbered_buffer = NULL;
}
if(upload_build_buffer(&seq_numbered_buffer, seq_n, buffer))
return 1;
此外,如果我运行valgrind,我会得到:
==2832== Invalid write of size 1
==2832== at 0x4026FBF: strncpy (mc_replace_strmem.c:339)
==2832== by 0x80490F7: upload_build_buffer (uftp_client.c:189)
==2832== by 0x8049606: client_upload_file (uftp_client.c:397)
==2832== by 0x804A30F: data_connection_proc (uftp_client.c:882)
==2832== by 0x804AE4B: main (uftp_client.c:1214)
==2832== Address 0x419b0c4 is 0 bytes after a block of size 52 alloc'd
==2832== at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==2832== by 0x8049062: upload_build_buffer (uftp_client.c:174)
==2832== by 0x8049606: client_upload_file (uftp_client.c:397)
==2832== by 0x804A30F: data_connection_proc (uftp_client.c:882)
==2832== by 0x804AE4B: main (uftp_client.c:1214)
==2832==
==2832== Invalid write of size 1
==2832== at 0x4026FCB: strncpy (mc_replace_strmem.c:339)
==2832== by 0x80490F7: upload_build_buffer (uftp_client.c:189)
==2832== by 0x8049606: client_upload_file (uftp_client.c:397)
==2832== by 0x804A30F: data_connection_proc (uftp_client.c:882)
==2832== by 0x804AE4B: main (uftp_client.c:1214)
==2832== Address 0x419b0c5 is 1 bytes after a block of size 52 alloc'd
==2832== at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==2832== by 0x8049062: upload_build_buffer (uftp_client.c:174)
==2832== by 0x8049606: client_upload_file (uftp_client.c:397)
==2832== by 0x804A30F: data_connection_proc (uftp_client.c:882)
==2832== by 0x804AE4B: main (uftp_client.c:1214)
我不知道如何调试这段代码。。
Valgrind输出告诉您几乎所有的东西——您在strncpy
调用中写过了缓冲区的末尾。函数中只有一个strncpy
调用。因此,从逻辑上讲,您把缓冲区大小或strncpy
参数搞砸了。