有人可以向我解释为什么这不起作用吗?程序似乎停在 sprintf(t->tuple[0], "abc");我不知道为什么。真的需要帮助。
int testRemoveMeio(){
int result, i;
struct list_t *list = list_create();
char *tdata[3] = {" ", "2014", "Fixe!"};
struct tuple_t *t = tuple_create2(3, tdata);
struct tuple_t *tdups[4];
struct entry_t *entries[4];
sprintf(t->tuple[0], "abc");
tdups[0] = tuple_dup(t);
entries[0] = entry_create(tdups[0]);
list_add(list, entries[0]);
//extra code similar to above
return 0;
}
编辑:
struct tuple_t {
int tuple_dimension;
char **tuple;
};
struct tuple_t *tuple_create2(int tuple_dim, char **tuple){
struct tuple_t *t = (struct tuple_t *) malloc(sizeof(struct tuple_t));
if(t == NULL)
return NULL;
t->tuple_dimension = tuple_dim;
t->tuple = tuple;
return t;
}
编辑以从评论中添加另一个示例:
#include <stdio.h>
#include <string.h>
int main(void)
{
char * s = "ABC";
printf("%s\n",s);
sprintf(s,"DEF");
printf("%s\n",s);
return 0;
}
最佳答案
我将您评论中的代码粘贴到问题中。我认为,由于相同的原因,该代码和您的原始代码都失败了:您正在修改字符串文字。
令人难过的是,在 C 中,像 "hello world"
这样的字符串文字是非法修改的,但可以分配给 char*
而无需 const 和转换。这很容易搞砸,因为修改这样的字符串是未定义的行为,因为它可能驻留在程序的只读内存中。
要修复它,试试这个:
char tdata[3][6] = {" ", "2014", "Fixe!"};
或者在你的第二个例子中:
char s[] = "ABC";
这样您就可以分配一个具有可写存储空间的实际字符数组。但是请始终使用 snprintf()
而永远不要使用 sprintf()
因为后者容易发生缓冲区溢出,这可能会导致程序崩溃或更糟。
关于C sprintf覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190118/