Warning: assignment makes integer from pointer without a cast - c

I'm learning C almost one year and it's my first time that I got that warnings.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <windows.h>
#include <string.h>
int socket_creation(FILE* fp){
int s;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET){
printf("Error occurred while creating socket: %d\n", WSAGetLastError());
fprintf(fp, "Error occurred while creating socket: %d\n", WSAGetLastError());
}
else{
printf("Socket creation was successful.\n");
fprintf(fp, "Socket creation was successful.\n");
}
return s;
}
void connect_to_server(int s, struct sockaddr_in ClientService, FILE* fp){
int cResult;
cResult = connect(s, (struct sockaddr*) &ClientService, sizeof(ClientService));
if (cResult == SOCKET_ERROR){
printf("connection to the server has been failed: %d\n", WSAGetLastError());
fprintf(fp, "connection to the server has been failed: %d\n", WSAGetLastError());
cResult = closesocket(s);
if (cResult == SOCKET_ERROR){
printf("error occurred while trying to close socket. \n");
fprintf(fp, "error occurred while trying to close socket. \n");
}
WSACleanup();
}
else{
printf("Connection to serevr has been made successfully. \n");
fprintf(fp, "Connection to serevr has been made successfully. \n");
}
}
int send_to_serv(char buffer[], int s){
int sendto;
sendto = send(s, buffer, 1024, 0);
if (sendto == -1)
printf("\nError: couldn't send the Code.\n", buffer);
else printf("\nCode: <%s> SENT.\n", buffer);
return sendto;
}
int recv_from_serv(int s, int* numberLines, FILE *fp){
int recvfrom;
char buffer[1024] = "";
recvfrom = recv(s, buffer, 1024, 0);
if (recvfrom == -1)
printf("\nError: couldn't receive Code. !\n");
else printf("\nRespond: <%s>, RECEIVED. \n", buffer);
fprintf(fp, "\n");
fprintf(fp, buffer);
*numberLines = atoi(buffer + 3);
return recvfrom;
}
int main() {
WSADATA info;
int error, s;
int sResults, sendError, recvError,convert2;
char buffer[1024] = "";
char recvbuf[1024] = "";
int numberLines, i, temp, convert;
char converted_num[1024] = "";
struct sockaddr_in ClientService;
FILE *fp = fopen("stored_data.txt", "w");
char* lines_array;
error = WSAStartup(MAKEWORD(2, 0), &info);
if (error != 0){
printf("WSAstartup failed with error: %d\n", error);
exit(1);
}
for (i=0; i <=numberLines; i++) {
lines_array[i]=NULL;
}
s = socket_creation(fp);
ClientService.sin_family = AF_INET;
ClientService.sin_addr.s_addr = inet_addr("54.209.143.42");
ClientService.sin_port = htons(6714);
connect_to_server(s, ClientService, fp);
strcpy(buffer, "100");
sendError = send_to_serv(buffer, s);
recvError = recv_from_serv(s, &numberLines, fp);
strcpy(buffer, "400");
sendError = send_to_serv(buffer, s);
recvError = recv_from_serv(s, &numberLines, fp);
printf("\nNumber of Lines are: %d\n", numberLines);
lines_array = malloc(sizeof(char*)*numberLines);
temp = numberLines;
for (i = 0; i < temp; i++){
convert = 5000001 + i;
_itoa(convert, converted_num, 10);
sendError = send_to_serv(converted_num, s);
convert2=atoi(convert);
convert=convert%10000;
if(convert2==0) {
for(i=0; i<=1024; i++) {
buffer[i]=0;
}
lines_array= (convert);
recv_from_serv(s, &numberLines, fp);
}
else{
for(i=0; i<=1024; i++) {
buffer[i]=0;
}
}
}
close(fp);
//system("PkAUSE>nul");
system("PAUSE");
return 0;
}
This is that output that my compiler (MinGW) giving to me:
finalproject1.c: In function main': finalproject1.c:87: warning:
assignment makes integer from pointer without a cast
finalproject1.c:113: warning: passing arg 1 ofatoi' makes pointer
from integer without a cast finalproject1.c:119: warning: assignment
makes pointer from integer without a cast finalproject1.c:133:3:
warning: no newline at end of file
Please help me I don't know what to do and my guid told me to "Google it" when I asked him to help me.

The line that triggers the warning is:
lines_array[i]=NULL;
and this variable is declared like so:
char* lines_array;
so you're cramming a pointer (the NULL macro expands to a pointer-type value on your system) into a single char, which won't fit and is a very strange thing to be doing.
Probably you wanted an array of character pointers, i.e.
char **lines_array;
but then you must of course allocate the array once you know how many lines you're going to be dealing with.

First of all, i can see you are using an integer numberLines as a condition in your for loop without initializing it first:
int numberLines;
for (i=0; i <=numberLines; i++) {
lines_array[i]=NULL;
}
Simply if you want to initialize your array to null you can initialize it as:
char* lines_array = null;
Try this and let me know if the warnings still exist.

Related

Server/client program behaves different after adding code in C

I'm on Windows. I have a server/client program that copies a file from client to server. Everthing works as expected until I add the code where I send the size of the file from client to server. When I remove the code it works fine again. The while() loop in my server normally loops 378 times the while() loop in my client also loops 378 times. After I add the code to send the file size the while() loop in my server loops 377 times, and that causes the failure. I don't get any errors but when I click on the copied file it doesn't show anything(because the server loops 377 instead of 378). I commented *** where the code is that I'm talking about. What is the cause of this and how can I solve it?
Edit: The server receives the size of the file successfully
functions:
int getSizeFile(FILE* file)
{
// get file size
FILE *f = file;
fseek(f, 0L, SEEK_END);
int sizeFile = ftell(f);
rewind(f);
return sizeFile;
}
static inline uint32_t ntohl_ch(char const* X)
{
uint32_t x; memcpy(&x, X, sizeof(x));
return ntohl(x);
}
server:
char ch[70];
printf("where do you want to save it(full path + name): ");
scanf_s("%s", ch, 70);
char c[70];
printf("which file you want to copy(full path + name): ");
scanf_s("%s", c, 70);
r = send(s, c, 70, 0); // B
if (r == SOCKET_ERROR)
{
printf("2 error: %d\n", WSAGetLastError);
}
FILE* copyFile;
fopen_s(&copyFile, ch, "wb");
if (copyFile == NULL)
{
printf("Error opening file\n");
}
char buf[BUFSIZE];
size_t size = BUFSIZE;
int counter = 0;
// *** receiving file size. This is the code
char b[8192];
r = recv(s, b, 8192, 0); // C
if (r == SOCKET_ERROR)
{
printf("error recv\n");
}
uint32_t test = ntohl_ch(&b[0]);
printf("%d\n", (int)test);
// *** Until here
while (1)
{
int res = recv(s, buf, BUFSIZE, 0);
if (res == SOCKET_ERROR)
{
printf("3 error %d\n", WSAGetLastError);
break;
}
size = fwrite(buf, 1, res, copyFile);
printf("size: %d\n", size);
printf("res: %d\n", res);
counter++;
printf("counter: %d\n", counter);
}
fclose(copyFile);
client:
char c[70];
res = recv(ClientSocket, c, 70, 0); // B
if (res == SOCKET_ERROR)
{
printf("Server disconeccted\n");
break;
}
FILE* originalFile;
fopen_s(&originalFile, c, "rb");
if (originalFile == NULL)
{
printf("Error opening file\n");
}
char buf[BUFSIZE];
size_t size = BUFSIZE;
int counter = 0;
// getting file size
int sizeFile = getSizeFile(originalFile);
// *** sending file size. This is the code
uint32_t num = htonl(sizeFile);
char* converted_num = (char*)&num;
res = send(ClientSocket, converted_num, sizeof(num), 0); // C
if (res == SOCKET_ERROR)
{
printf("error send\n");
}
// *** Until here
while (size == BUFSIZE)
{
size = fread(buf, 1, BUFSIZE, originalFile);
int r = send(ClientSocket, buf, size, 0);
if (r == SOCKET_ERROR)
{
printf("1 error: %d\n", WSAGetLastError);
break;
}
printf("size: %d\n", size);
printf("r: %d\n", r);
counter++;
printf("counter: %d\n", counter);
}
printf("out of while loop\n");
fclose(originalFile);

Segmentation fault using the buffer recived from recv() tcpServer c

I'm trying to create an application client/server in c, but after recv() when I try to use the buffer received the program give segmentation fault (core dump created), I can't work out it.
This is my code at server side:
int req_socket_id;
int comunication_socket_id;
struct sockaddr_in server_add;
struct sockaddr_in client_add;
socklen_t client_add_size;
char buffer[255];
//char mess[1024];
int i, n;
//int index;
unsigned int num;
// AF_INET = famiglia di indirizzi iPv4
req_socket_id = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(req_socket_id<0)
{
printf("Socket initialization failed !!");
return -1;
}
e
memset(&server_add, 0, sizeof(server_add)); // azzeramento struttura
server_add.sin_family = AF_INET; // dominio indirizzi IP
server_add.sin_addr.s_addr = 0; // indirizzo IP
server_add.sin_port = htons(23165); // numero di porta UDP
if(bind(req_socket_id, (struct sockaddr*) &server_add, sizeof(server_add)) < 0)
{
perror("\nErrore associazione porta e socket!\n");
close(req_socket_id);
return -1;
}
if(listen(req_socket_id, 1)<0)
{
perror("\nErrore nell'ascolto!\n");
close(req_socket_id);
return -1;
}
while(1)
{
client_add_size = sizeof(client_add);
comunication_socket_id = accept(req_socket_id, (struct sockaddr*) &client_add, &client_add_size);
if(comunication_socket_id>=0)
{
//index = 0;
char tmp[100];
while(1)
{
printf("\nOk");
//n = recv(comunication_socket_id, (char*) buffer, sizeof(buffer)+1, 0);
//n = recv(comunication_socket_id, (void*) buffer, sizeof(buffer)+1, 0);
n = recv(comunication_socket_id, buffer, sizeof(buffer)+1, 0);
printf("\nReceved! n: %d", n);
printf("\nReceved: %s", buffer);
if(strcmp(buffer, "end")==0)
{
close(comunication_socket_id);
printf("\n...socket closed");
return -1;
}
[...]
and this is client side code :
unsigned long start, now;
unsigned int *num = (unsigned int*)buffer;
int i, n;
TCPclient_send(buffer, strlen(buffer)+1);
printf("\nSent: |%s|\n", buffer);
start = clock(); // tempo iniziale attesa
now = clock(); // tempo attuale
while ((now - start) < TIMEOUT)
{
if ((n = TCPclient_receive(&buffer[i], sizeof(buffer)-i)) > 0)
{
i += n;
if (i >= sizeof(unsigned int))
{
// risposta completa
printf("Receved number %u.\r\n", ntohl(*num));
TCPclient_disconnect();
return 0;
}
}
now = clock();
}
printf("No answer receved!\r\n");
TCPclient_disconnect();
Console server side output:
davide#davide-VirtualBox:~/Documenti/RubricaTCP$ ./TCPserver
Ok
Receved! n: 11
Errore di segmentazione (core dump creato) //-->segmentation fault, end of process
Console client side output:
Insert the command (end to close): SET=A;A;A;
Sent: |SET=A;A;A;|
No answer receved!
PS: this is my first application with sockets, so it's possible that i've done some stupid mistakes. I looked for answers in many topics, but i didn't find anything that can work out it.
Thank you very much
n = recv(comunication_socket_id, buffer, sizeof(buffer)+1, 0);
sizeof(buffer)+1 is inherently incorrect. It should be sizeof(buffer). You are using memory that does not exist.
printf("\nReceved! n: %d", n);
OK.
printf("\nReceved: %s", buffer);
Wrong. This should be
printf("\nReceved: %.*s", n, buffer);
Then:
if(strcmp(buffer, "end")==0)
This is also wrong. There is no guarantee that you've received a null terminated string or a complete command. It's a byte-stream protocol. If you want messages you have to implement them yourself. It is rarely correct to write networking code or any I/O code for that matter that doesn't have read or receive loops.

Socket Programming: Bad address Error in read() when used in loop

I was trying to implement FTP Server as a part of an assignment and I wrote the following code to implement GET Command, which essentially reads file1 from server and stores it in file2.
int getCommandImpl(int clientSocket, char *file1, char *file2){
char *messageContent;
char buffer[256], userCommand[256], *tempString ;
int messageHead, endOfTransfer =0;
int messageLength;
sprintf(userCommand, "GET %s", file1);
messageLength = write(clientSocket,userCommand,strlen(userCommand));
if(messageLength <0){
perror("Error sending data to server in RETR");
return 0;
}
FILE *fp;
fp = fopen(file2, "w");
if(fp==NULL){
printf("%s Can not be created\n", file2);
return 0;
}
printf("Writing to file %s\n", file2);
while(!endOfTransfer){
messageLength = read(clientSocket, buffer, strlen(buffer)-1);
if(messageLength == -1){
perror("GET: Error in read() ");
break;
}
//puts(buffer);
printf("Buffer is %s with len %d\n", buffer, strlen(buffer));
tempString = strdup(buffer);
messageHead = atoi(strtok(tempString, " "));
messageContent = strtok(NULL, " ");
if(messageHead == 0 && strlen(messageContent)==0){ //End of file transfer
endOfTransfer = 1;
break;
}
fwrite(messageContent, sizeof(char), sizeof(messageContent), fp);
memset(buffer,0,sizeof(buffer));
printf("Buffer is %s with len %d\n", buffer, strlen(buffer));
}
fclose(fp);
return 1;
}
While running it, I am always getting the error "GET: Error in read() : Bad address". If I remove the statement
memset(buffer,0,sizeof(buffer));
I am getting a segmentation fault. I am assuming that the error has something to do with the string buffer being empty from the second iteration.
Any help to solve this will be highly appreciated.

c program not writing same result as it is displaying

My C program is not writing to a file the same data that it is displaying. how do i save what is outputted to the screen in a file. I am trying to save a webpage, the file name is defined by the third option, [site] [page] [path]
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
int create_tcp_socket();
char *get_ip(char *host);
char *build_get_query(char *host, char *page);
void usage();
#define HOST "coding.debuntu.org"
#define PAGE "/"
#define PORT 80
#define USERAGENT "HTMLGET 1.0"
#define OS "mac osx"
int main(int argc, char **argv)
{
struct sockaddr_in *remote;
int sock;
int tmpres;
char *ip;
char *get;
char buf[BUFSIZ+1];
char *host;
char *page;
char *HTMLfile;
if(argc == 1){
usage();
exit(2);
}
host = argv[1];
if(argc > 2){
page = argv[2];
}else{
page = PAGE;
}
HTMLfile = argv[3];
sock = create_tcp_socket();
ip = get_ip(host);
fprintf(stderr, "<!--\nIP is %s\n", ip);
remote = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in *));
remote->sin_family = AF_INET;
tmpres = inet_pton(AF_INET, ip, (void *)(&(remote->sin_addr.s_addr)));
if( tmpres < 0)
{
perror("Can't set remote->sin_addr.s_addr");
exit(1);
}else if(tmpres == 0)
{
fprintf(stderr, "%s is not a valid IP address\n", ip);
exit(1);
}
remote->sin_port = htons(PORT);
if(connect(sock, (struct sockaddr *)remote, sizeof(struct sockaddr)) < 0){
perror("Could not connect");
exit(1);
}
get = build_get_query(host, page);
fprintf(stderr, "nQuery is:\n<<START>>\n%s<<END>>\n-->\n", get);
//Send the query to the server
int sent = 0;
while(sent < strlen(get))
{
tmpres = send(sock, get+sent, strlen(get)-sent, 0);
if(tmpres == -1){
perror("Can't send query");
exit(1);
}
sent += tmpres;
}
//now it is time to receive the page
memset(buf, 0, sizeof(buf));
int htmlstart = 0;
char * htmlcontent;
while((tmpres = recv(sock, buf, BUFSIZ, 0)) > 0){
if(htmlstart == 0)
{
/* Under certain conditions this will not work.
* If the \r\n\r\n part is splitted into two messages
* it will fail to detect the beginning of HTML content
*/
htmlcontent = strstr(buf, "\r\n\r\n");
if(htmlcontent != NULL){
htmlstart = 1;
htmlcontent += 4;
}
}else{
htmlcontent = buf;
}
if(htmlstart){
fprintf(stdout, "%s", htmlcontent);
}
FILE *f;
f = fopen(HTMLfile, "w");
fprintf(f, "%s", htmlcontent); //stderr, "%s"
fclose(f);
memset(buf, 0, tmpres);
}
if(tmpres < 0)
{
perror("Error receiving data");
}
free(get);
free(remote);
free(ip);
close(sock);
return 0;
}
void usage()
{
fprintf(stderr, "USAGE: htmlget host [page]\n\
\thost: the website hostname. ex: coding.debuntu.org\n\
\tpage: the page to retrieve. ex: index.html, default: /\n");
}
int create_tcp_socket()
{
int sock;
if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror("Can't create TCP socket");
exit(1);
}
return sock;
}
char *get_ip(char *host)
{
struct hostent *hent;
int iplen = 15; //XXX.XXX.XXX.XXX
char *ip = (char *)malloc(iplen+1);
memset(ip, 0, iplen+1);
if((hent = gethostbyname(host)) == NULL)
{
herror("Can't get IP");
exit(1);
}
if(inet_ntop(AF_INET, (void *)hent->h_addr_list[0], ip, iplen) == NULL)
{
perror("Can't resolve host");
exit(1);
}
return ip;
}
char *build_get_query(char *host, char *page)
{
char *query;
char *getpage = page;
char *tpl = "GET /%s HTTP/1.0\r\nHost: %s\r\nUser-Agent: %s\r\n\r\n";
if(getpage[0] == '/'){
getpage = getpage + 1;
fprintf(stderr,"Removing leading \"/\", converting %s to %s\n", page, getpage);
}
// -5 is to consider the %s %s %s in tpl and the ending \0
query = (char *)malloc(strlen(host)+strlen(getpage)+strlen(USERAGENT)+strlen(OS)+strlen(tpl)-5);
sprintf(query, tpl, getpage, host, USERAGENT);
return query;
// FILE *f;
// f = fopen(HTMLfile, "w");
// fprintf(f, htmlcontent);
// fclose(f);
}
Here is where i am saving the file:
FILE *f;
f = fopen(HTMLfile, "w");
fprintf(f, "%s", htmlcontent); //stderr, "%s"
fclose(f);
Here is the result that it saves for my question (This Page)
(['_setCustomVar', 1, 'tags', '|c|file|networking|']);
_gaq.push(['_trackPageview']);
var _qevents = _qevents || [];
(function () {
var ssl='https:'==document.location.protocol,
s=document.getElementsByTagName('script')[0],
ga=document.createElement('script');
ga.type='text/javascript';
ga.async=true;
ga.src=(ssl?'https://ssl':'http://www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(ga,s);
var sc=document.createElement('script');
sc.type='text/javascript';
sc.async=true;
sc.src=(ssl?'https://secure':'http://edge')+'.quantserve.com/quant.js';
s.parentNode.insertBefore(sc,s);
})();
_qevents.push({ qacct: "p-c1rF4kxgLUzNc" });
</script>
</body>
</html>
FILE *f;
f = fopen(HTMLfile, "w");
fprintf(f, "%s", htmlcontent); //stderr, "%s"
fclose(f);
Rather than opening and closing the file each time through the loop, you should open
it once before the loop, keep it open while you're writing into it, then close it after
the loop.
Instead of opening the file with "w" use "a". Better yet, only open the file once.
f = fopen(HTMLfile, "a");
w" write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
"a" append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.

C - irc bot skeleton

#include <winsock2.h>
#include <stdio.h>
const int PORT = 6667;
const char *SERVER = "irc.freenode.org";
const char *CHAN = "#channela";
const char *NICK = "loveMilk";
const int MAX_BUFF_SIZE = 512;
int sock_conn(SOCKET *socketn, const char *HOST, int portn);
int sock_send(SOCKET *socketn, char* msg, ...);
int main(int argc, char *argv[])
{
WSADATA wsadata;
char buff[MAX_BUFF_SIZE];
char oBuff[MAX_BUFF_SIZE];
int buffRec;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
return 0;
SOCKET sock;
if(sock_conn(&sock, SERVER, PORT) != 0)
{
WSACleanup();
return 0;
}
printf("connected.\n");
sock_send(&sock, "USER %s \"\" \"127.0.0.1\" :%s\r\n", NICK, NICK);
sock_send(&sock, "NICK %s\r\n", NICK);
Sleep(100);
sock_send(&sock, "JOIN %s\r\n", CHAN);
printf("Joined channel.\n");
while(1)
{
memset(buff, 0, MAX_BUFF_SIZE);
memset(oBuff, 0, MAX_BUFF_SIZE);
buffRec = recv(sock, buff, MAX_BUFF_SIZE, 0);
if((buffRec == 0) || (buffRec == SOCKET_ERROR)) break;
if(buff[0] != ':')
{
strcpy(oBuff, "PONG :");
printf("PONG");
sock_send(&sock, oBuff);
}
else
{
if(strstr(buff, "PRIVMSG"))
{
int i, num = 0;
for(i = 0; i < strlen(buff); ++i) if(buff[i] = ' ') ++num;
char** parts = malloc(sizeof(char*) * num);
char *p;
p = strtok(buff, " ");
int j = 0;
while(p != NULL)
{
parts[j] = p;
j++;
p = strtok(NULL, " ");
}
free(parts);
}
}
}
closesocket(sock);
return 1;
}
int sock_conn(SOCKET *socketn, const char *HOST, int portn)
{
WSADATA wsadata;
SOCKADDR_IN sockA;
LPHOSTENT hostE;
if(WSAStartup(MAKEWORD(2,2), &wsadata) == -1) return -1;
if(!(hostE = gethostbyname(HOST)))
{
WSACleanup();
return -1;
}
if ((*socketn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
WSACleanup();
return -1;
}
sockA.sin_family = AF_INET;
sockA.sin_port = htons(portn);
sockA.sin_addr = *((LPIN_ADDR)*hostE->h_addr_list);
if(connect(*socketn, (LPSOCKADDR)&sockA, sizeof(struct sockaddr)) == SOCKET_ERROR)
{
WSACleanup();
return -1;
}
}
int sock_send(SOCKET *socketn, char* msg, ...)
{
char buff[MAX_BUFF_SIZE];
va_list va;
va_start(va, msg);
vsprintf(buff, msg, va);
va_end(va);
send(*socketn, buff, strlen(buff), 0);
return 1;
}
If I try to print buff after the if(strstr(buff, "PRIVMSG")) it crashes.
The while with the strtok won't work, if I try to reach parts[0] it crashes.
I tried to print parts[0] but shows nothing, tried to print during the while loop, shows nothing.
why?
You don't terminate your strings!
Edit the receiving part as this:
buffRec = recv(sock, buff, MAX_BUFF_SIZE, 0);
if((buffRec == 0) || (buffRec == SOCKET_ERROR)) break;
/* New line: Terminate buffer as a string */
buff[buffRec] = '\0';
As the other answer points out, a character array must end with '\0' to be considered a string. I think that C doesn't distinguish between the two, but you need the '\0' to signify the end of string. This could be why strstr(buff, "PRIVMSG")) isn't returning anything. It may default to null (thus not satisfying your if) because it doesn't think it has been passed a string.
'strtok(string, delimiter)' breaks an input string into tokens by using the delimiter. Here, you have passed it NULL as its string and " " as its delimiter. I am unfamiliar with many string functions (still learning C myself), but I think this is incorrect usage in your code.
parts[] does not seem to be defined in the code you've given. Its first use is where you try to store data in it for the inner while loop. Are there any other parts to the program that are not shown?

Resources