在不使用printf()时获取malloc错误 #包括 #包括 类型定义结构列表 { int-num; 结构lis*下一步; }名单; 无效乐趣(列表**h,整数){ *h=malloc(sizeof(列表)*nu); 列表*p=*h; int i=1; 列表*nextx; 而(inum=i; p->next=nextx; //printf(“%d\n”,nextx); p+=1; i++; } p->next=NULL; } int main(int argc,char const*argv[] { list*first=NULL; 乐趣(第一,10); 免费(第一); 返回0; }
我正在学习c语言的列表 每当运行此代码时,都会出现malloc错误 如果我注释掉显示下一个节点的在不使用printf()时获取malloc错误 #包括 #包括 类型定义结构列表 { int-num; 结构lis*下一步; }名单; 无效乐趣(列表**h,整数){ *h=malloc(sizeof(列表)*nu); 列表*p=*h; int i=1; 列表*nextx; 而(inum=i; p->next=nextx; //printf(“%d\n”,nextx); p+=1; i++; } p->next=NULL; } int main(int argc,char const*argv[] { list*first=NULL; 乐趣(第一,10); 免费(第一); 返回0; },c,malloc,C,Malloc,我正在学习c语言的列表 每当运行此代码时,都会出现malloc错误 如果我注释掉显示下一个节点的printf(“%d\n”,nextx);,它工作正常 发生了什么?在循环的最后一次运行中,您的代码执行以下操作: #include <stdio.h> #include <stdlib.h> typedef struct lis { int num; struct lis * next; } list; void fun(list ** h, int nu)
printf(“%d\n”,nextx);
,它工作正常
发生了什么?在循环的最后一次运行中,您的代码执行以下操作:
#include <stdio.h>
#include <stdlib.h>
typedef struct lis
{
int num;
struct lis * next;
} list;
void fun(list ** h, int nu) {
*h = malloc(sizeof(list)*nu);
list *p = *h;
int i=1;
list * nextx;
while(i<=nu) {
nextx = p + 1;
p->num = i;
p->next = nextx;
//printf("%d\n", nextx);
p += 1;
i++;
}
p->next = NULL;
}
int main(int argc, char const *argv[])
{
list * first = NULL;
fun(&first,10);
free(first);
return 0;
}
先退出循环一步,然后正确设置最后一个元素:
nextx = p+1; // points one past the last array' element
p->num = nu-1; // ok
p->next = p+1; // probably not what you wanted, but not a fault per se
p += 1; // This is the cause of your problem
i++; // out of the loop...
p->next = NULL; // dereference out of array pointer!
while(inxt=NULL;
p->num=nu-1;
在循环的最后一次运行中,您的代码执行以下操作:
#include <stdio.h>
#include <stdlib.h>
typedef struct lis
{
int num;
struct lis * next;
} list;
void fun(list ** h, int nu) {
*h = malloc(sizeof(list)*nu);
list *p = *h;
int i=1;
list * nextx;
while(i<=nu) {
nextx = p + 1;
p->num = i;
p->next = nextx;
//printf("%d\n", nextx);
p += 1;
i++;
}
p->next = NULL;
}
int main(int argc, char const *argv[])
{
list * first = NULL;
fun(&first,10);
free(first);
return 0;
}
先退出循环一步,然后正确设置最后一个元素:
nextx = p+1; // points one past the last array' element
p->num = nu-1; // ok
p->next = p+1; // probably not what you wanted, but not a fault per se
p += 1; // This is the cause of your problem
i++; // out of the loop...
p->next = NULL; // dereference out of array pointer!
while(inxt=NULL;
p->num=nu-1;
请发布一个完整的示例。确保显示所有变量声明和初始化。同时显示您收到的确切错误消息。如果添加/删除printf()
语句会改变您是否出现错误,这几乎总是表明您在程序中的某个地方导致了未定义的行为。UB并不总是触发错误,它只是破坏内存,然后取决于您之后的操作是否出现错误。您得到的确切错误是什么?问问自己p
po在循环退出时输入,并询问p->next=NULL;
随后会做什么。请发布一个完整的示例。确保显示所有变量声明和初始化。同时显示您得到的确切错误消息。如果添加/删除printf()
语句会改变您是否出现错误,这几乎总是表明您在程序中的某个地方导致了未定义的行为。UB并不总是触发错误,它只是破坏内存,然后取决于您之后的操作是否出现错误。您得到的确切错误是什么?问问自己p
po在循环退出时输入,并询问p->next=NULL;
随后会做什么。