Thread: Few problems I'm having with c

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    1

    Few problems I'm having with c

    Ok first question regarding to pointers (assuming the code is being run on windows and not linux):
    we can do this :


    int i = 10;
    int *p1 = &i;
    int *p2 = p2;
    int *p3 = p3;


    so we create an int with the value of 10
    and 3 pointers the first points to the address of i, the second points to the first pointer which points to address of i, and the third points to the address of the second pointer which points to the address of the first pointer which points to the address of i.
    So they all pointing at the same address which holds the value 10.


    Now if I were to do this :
    char ch[] = "Hello";
    char *p1 = ch;
    char *p2 = p1;
    char *p3 = p2;
    printf("ch : %s\n", ch);
    printf("p1 address [%d] value is %s\n", p1, *p1);
    printf("p2 address [%d] value is %s\n", p2, *p2);
    printf("p3 address [%d] value is %s\n", p3, *p3);


    I'll get error after printing ch and I don't understand why,
    I though that if I write char *p1 = ch; that means p1 points to the address of the first character in the array and the other pointers point to pointer 1 eventually which points to the address of the first element in the array BUT the program crashes and I don't understand why ..


    Another question is when should I use characters array and when should I use pointers ? From what I've read, and please correct me if I'm wrong, character pointers are not modify-able unless you allocate memory to it using malloc() and then you can read AND write to the different addresses but if you were to do something like
    char *p = "str";
    this is not writeable and it's constant, and about what happens if you do something like
    char *p1 = "str";
    char *p2 = p1;


    I'm not sure if it's writeable, heck, I'm not even sure if I can do it since I tried to do it in my example shown in question #1 and the program crashes.


    My last question is this:
    I decided to make a File Ceasar Shift program, I enter the shift and the file to encrypt through the arguments in the cmd, I've created a file named CryptoFile.txt which holds some text in it, When I run the program this is what I've executed in the cmd :
    "FileCaesarShift.exe 15 CryptoFile.txt"
    so the shift is 15 and the file to encrypt is CryptoFile.txt
    Now.. although a new file called CryptoFile.enc is being crated it's EMPTY and I don't see why, I've tried to look for the problem but failed.
    Here's the code :
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    void copyFileExtension(char*, char*);
    int getFileNameLengthWithoutExtension(char*);
    int getFileExtensionLength(char*);
    void copyFileNameWithoutExtension(char*, char*);
    
    
    int main(int argc, char *argv[])
    {
    	int shift = atoi(argv[1]);
    	int byte;
    	char *fileName = (char*)argv[2];
    	char *fileExtension = malloc(getFileExtensionLength(fileName) + 1);
    	copyFileExtension(fileExtension, fileName);
    	char *newFileName = malloc(getFileNameLengthWithoutExtension(fileName) + 5);
    	copyFileNameWithoutExtension(newFileName, fileName);
    	FILE *f_in;
    	FILE *f_out;
    	f_in = fopen(fileName, "r");
    	if (strcmp(fileExtension, "enc") == 0)
    	{
    		// We want to decrypt the file
    		puts("dec");
    		strcat(newFileName, ".dec");
    		f_out = fopen(newFileName, "w");
    		while ((byte = fgetc(f_in)) != EOF)
    		{
    			fputc(byte - shift, f_out);
    		}
    	}
    	else
    	{
    		puts("enc");
    		// We want to encrypt the file
    		strcat(newFileName, ".enc");
    		f_out = fopen(newFileName, "w");
    		while ((byte = fgetc(f_in)) != EOF)
    		{
    			fputc(byte + shift, f_out);
    		}
    	}
    	fclose(f_in);
    	fclose(f_out);
    	return 0;
    }
    
    
    void copyFileExtension(char *fileExtension, char *fileName)
    {
    	char *token = strtok(fileName, ".");
    	token = strtok(NULL, ".");
    	strcpy(fileExtension, token);
    }
    
    
    int getFileNameLengthWithoutExtension(char *fileName)
    {
    	if (*fileName && *fileName != '.')
    	{
    		return 1 + getFileNameLengthWithoutExtension(++fileName);
    	}
    	return 0;
    }
    
    
    int getFileExtensionLength(char *fileName)
    {
    	int foundExt = 0;
    	int len = 0;
    	while(*fileName)
    	{
    		if (foundExt == 1)
    		{
    			len++;
    		}
    		if (*fileName == '.')
    		{
    			foundExt = 1;
    		}
    		fileName++;
    	}
    	printf("ext len is %d\n", len);
    	return len;
    }
    
    
    void copyFileNameWithoutExtension(char* dest, char *source)
    {
    	char *fileNameWithoutExtension = strtok(source, ".");
    	strcpy(dest, fileNameWithoutExtension);
    }

    I guess it's a problem with the while statement
    "while ((byte = fgetc(f_in)) != EOF)"


    because I get inside the else statement and a proof of it is the printf to the console saying "enc" + a new file being created which is enough proof that I get inside the else statement BUT as I said the file is empty so it doesn't go through the while loop but I don't see what's wrong with it, to me it looks fine :|

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    so we create an int with the value of 10
    and 3 pointers the first points to the address of i, the second points to the first pointer which points to address of i, and the third points to the address of the second pointer which points to the address of the first pointer which points to the address of i.
    So they all pointing at the same address which holds the value 10.
    Nope - only p1 points to an integer. p2 and p3 are just pointers initialised with their own garbage value.

    char *p = "str";
    this is not writeable and it's constant, and about what happens if you do something like
    char *p1 = "str";
    char *p2 = p1;
    No, p2 is just as unwriteable as p1 is.
    You should really write
    const char *p1 = "str";
    then at least the compiler would warn you if you used p1 in an l-value context.

    The main problem with the code is a lack of error checking on opening the files.
    Code:
    $ gdb ./a.out
    GNU gdb (Ubuntu/Linaro 7.3-0ubuntu2) 7.3-2011.08
    Copyright (C) 2011 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "x86_64-linux-gnu".
    For bug reporting instructions, please see:
    <http://bugs.launchpad.net/gdb-linaro/>...
    Reading symbols from /home/sc/Documents/a.out...done.
    (gdb) run 5 bar.txt
    Starting program: /home/sc/Documents/a.out 5 bar.txt
    ext len is 3
    enc
    
    Program received signal SIGSEGV, Segmentation fault.
    _IO_getc (fp=0x0) at getc.c:40
    40      getc.c: No such file or directory.
            in getc.c
    (gdb) bt
    #0  _IO_getc (fp=0x0) at getc.c:40
    #1  0x000000000040096d in main (argc=3, argv=0x7fffffffe0c8) at bar.c:41
    (gdb) up
    #1  0x000000000040096d in main (argc=3, argv=0x7fffffffe0c8) at bar.c:41
    41          while ((byte = fgetc(f_in)) != EOF)
    (gdb) print fileName
    $1 = 0x7fffffffe400 "bar"
    You see, you messed up the input filename in an attempt to extract the extension.
    It used to be bar.txt, but now it's just bar.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    It seems like you have three questions here (pointers, character array vs pointer, ceasar shift). Maybe you could post each one in a separate thread so its easier for the forum to take them one by one?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with HW Problems!!!
    By NikeLover in forum C++ Programming
    Replies: 12
    Last Post: 02-23-2011, 05:17 AM
  2. fread problems or memory problems
    By Lechuza in forum C Programming
    Replies: 1
    Last Post: 03-22-2009, 12:45 PM
  3. c problems
    By hitman_here in forum C Programming
    Replies: 5
    Last Post: 02-06-2006, 05:54 PM
  4. Linking problems, class problems
    By Kheila in forum C++ Programming
    Replies: 12
    Last Post: 11-22-2005, 01:47 AM
  5. Problems
    By Unregistered in forum C++ Programming
    Replies: 0
    Last Post: 02-28-2002, 03:59 AM