LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Two variables sharing memory? (https://www.linuxquestions.org/questions/programming-9/two-variables-sharing-memory-308161/)

Ephracis 03-31-2005 06:24 AM

Two variables sharing memory?
 
I was just playing around with some C code, trying to get the hang of it, and ended up with this:

Code:

#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[]) {

        if (argc == 3) {

                // get the first argument
                char first[strlen(argv[1]+1)];
                strncpy(first, argv[1], sizeof(first)+2);

                // get the second argument
                char second[strlen(argv[2]+1)];
                int i;
                for (i = 0; i < strlen(argv[2]) && argv[2][i] != ':'; i++)
                        second[i] = argv[2][i];
                second[i] = '\0';
                printf("0: check: %s\n", second);

                char port_str[strlen(argv[2]+2)-strlen(second)];
                printf("1: check: %s\n", second);

                for (int c = 0; c < sizeof(port_str); c++)
                        port_str[c] = '\0';
                printf("2: check: %s\n", second);

                int j;
                printf("3: check: %s\n", second);
                port_str[0] = 'a';
                port_str[1] = '\0';
                printf("4: check: %s\n", second);

        } else {
                printf("wrong syntax\n");
        }
}

I wanted to make a program that takes the syntax "./prog ip1 ip2:port". The wierd this is that when I change the port_str into just an "a" the last (4th) check of the "second"-variable shows that it has changed. Here is the output:

Code:

$ gcc blahfan.c -o temp -std=c99
$ ./temp 10.11.1.11 22.222.2.22:1 
0: check: 22.222.2.22
1: check: 22.222.2.22
2: check: 22.222.2.22
3: check: 22.222.2.22
4: check: a

I want "second" to stay intact. It is done, it was perfect, but then it got messed up when I changed port_str. What am I doing wrong?

puffinman 03-31-2005 11:47 PM

port_str and second are pointing to the same place in memory. I'll bet that the port_str[c] = "\0" isn't executing at all, and that the length of that array is 0. I'll go see...

jschiwal 04-01-2005 12:18 AM

char first[strlen(argv[1]+1)];

First of all, the length should be known at compile time to be able to determine what the length of first should be. Otherwise you need to have first and second be dynamically allocated, which will probably mean that they should be pointers to an array of char.

Second, I think you wanted [ strlen(argv[1]) + 1 ]
You are checking the length of the string starting with the second character, rather then adding one to the string length.


All times are GMT -5. The time now is 10:36 PM.