在这个问题,有人建议意见,我应该不会投的结果malloc
,即
int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
而不是:
int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
为什么会这样呢?
如果我malloc
在我的代码中使用:
int *x = malloc(sizeof(int));
Run Code Online (Sandbox Code Playgroud)
我收到以下警告gcc
:
new.c:7: warning: implicit declaration of function ‘malloc’
new.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’
Run Code Online (Sandbox Code Playgroud) 我目前正在重写链表模块,我收到一些奇怪的错误.
在两个IDE(Netbeans和Visual Studio Express)中,我收到一个警告,即malloc未定义,并且我的linkedlist.c文件中找不到的函数也没有定义.
下面是我的3个文件.
main.c中
#include <stdlib.h>
#include <stdio.h>
#include "linkedlist.h"
int main(void){
struct linked_list * l_list;
l_list = new_list();
printf("%i", l_list->length);
getchar();
return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
linkedlist.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
struct linked_list{
int length;
struct linked_list_node * head_node_ptr;
};
struct linked_list_node{
struct linked_list_node * prev_node_ptr;
struct linked_list_node * next_node_ptr;
struct linked_list_data * head_data_ptr;
};
struct linked_list_data{
struct linked_list_data * prev_data_ptr;
struct linked_list_data * next_data_ptr;
void * data;
};
struct linked_list * new_list();
#endif
Run Code Online (Sandbox Code Playgroud)
linkedlist.c
#include "linkedlist.h" …
Run Code Online (Sandbox Code Playgroud) 客户的代码期望malloc.h
在“通常的可疑”位置之一中找到包含文件。在我的Mac,AFAICT,没有malloc.h
,至少没有在任何地方,你会期望找到它,例如/usr/include
,/usr/local/include
或/opt/local/include
。由于malloc()
通常在 中定义stdlib.h
,并且由于代码无论如何都包含 stdlib.h,因此我能够通过注释掉malloc.h
. 我正在用gcc
.
但有两个问题:我的 gcc 不知何故搞砸了?那个文件应该在那里?此外,代码炸弹几乎立即出现了一个我还无法追踪到的段错误。这可能是使用错误的后果malloc()
吗?
#if 0
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <malloc.h>
#define ColSize 2
void inputData(double*, int*, int i, int CSize);
void printdata(double*, int*, int i, int CSize);
int main(void)
{
double *RATE;
int *MIN_BALANCE;
int i, CSize;
RATE = (double*)malloc(sizeof(double)*ColSize);
MIN_BALANCE = (int*)malloc(sizeof(int)*ColSize);
i = 0;
CSize = ColSize;
inputData(RATE, MIN_BALANCE, i, CSize);
printdata(RATE, MIN_BALANCE, i, CSize);
free(RATE);
free(MIN_BALANCE);
return 0;
}
void inputData(double *RATE, int *MIN_BALANCE, int i, int CSize)
{
for (i = 0; i < CSize; i++)
{
scanf("%lf", …
Run Code Online (Sandbox Code Playgroud)